10

js / jQuery:

$('input[type=checkbox]').click(function(){
  // Does not fire if I click a <input type="checkbox" disabled="disabled" />
});

誰かが無効なチェックボックスをクリックしたときにjQueryで何かが起こるようにするにはどうすればよいですか?

4

4 に答える 4

12

readonlyfromの使用に関するコメントをもう一度お読みJoãoSilvaください。これを使用して、クリックイベントのロジックに接続できます。

を使用readonlyすると、同じように無効な外観が得られますdisabledが、それでもクリックできます。

次のように読み取り専用を使用します。

<input type="checkbox" readonly="readonly">​

次に、読み取り専用が設定されている場合は、スクリプトでイベントをキャンセルします。

$('input[type=checkbox]').click(function() {
    var isReadOnly = $(this).attr("readonly") === undefined ? false : true;

    if (isReadOnly) {
        return false;
    }

    // other code never executed if readonly is true.
});
​

デモ

于 2012-09-16T16:18:15.007 に答える
9

すべてのブラウザでクリックイベントを確実にキャプチャすることはできません。最善の策は、クリックをキャプチャするために透明な要素を上に配置することです。

HTML

<div style="display:inline-block; position:relative;">
  <input type="checkbox" disabled="disabled" />
  <div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>​

JavaScript

$(':checkbox:disabled').next().click(function(){
    var checkbox = $(this.prevNode);
    // Does fire now :)
});

注:これは、私が改善したこの質問からのアイデアです。

于 2012-09-16T16:11:51.313 に答える
1

できません...しかし、透明な背景を持つ入力の上にdivを配置し、そのdivにクリック関数を定義することで偽造することができます。

$('input').each(function(){
    if(true == ($(this).prop('disabled'))){
        var iTop = $(this).position().top;
        var iLeft = $(this).position().left;
        var iWidth = $(this).width();
        var iHeight = $(this).height();
    $('body').append('<div class="disabledClick" style="position:absolute;top:'+iTop+'px;left:'+iLeft+'px;width:'+iWidth+'px;height:'+iHeight+'px;background:transparent;"></div>');    
    }       
});

//delegate a click function for the 'disabledClick'.


$('body').on('click', '.disabledClick', function(){
   console.log('This is the click event for the disabled checkbox.');
});

これが動作するjsFiddleです

于 2012-09-16T16:15:11.033 に答える
0

<div>チェックボックスの上にブロックレイヤーを追加する他のオプションはありません。したがって、解決策は次のようになります。

function addDisabledClickHandler(el, handler) {
    $("<div />").css({
        position: "absolute",
        top: el.position().top,
        left: el.position().left,
        width: el.width(),
        height: el.height()
    }).click(handler).appendTo("body");
}

var el = $("input[type='checkbox']");
addDisabledClickHandler(el, function() {
    alert("Clicked");
});​

デモ:http: //jsfiddle.net/q6u64/

于 2012-09-16T16:06:49.140 に答える