如何在禁用复选框上检测.click()

时间:2012-09-16 16:04:03

标签: javascript jquery

JS / jQuery的:

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

当有人点击禁用的复选框时,如何在jQuery中发生某些事情?

4 个答案:

答案 0 :(得分:12)

再次阅读有关使用readonly中的JoãoSilva的评论。您可以使用它并将其与click事件中的某些逻辑连接。

使用readonly会为您提供禁用的外观,就像disabled一样,但它仍然允许您点击它。

像这样使用readonly:

<input type="checkbox" readonly="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.
});
​

DEMO

答案 1 :(得分:8)

您将无法在所有浏览器中可靠地捕获点击事件。最好的办法是在上方放置一个透明元素来捕捉点击。

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 :)
});

注意:这是this question的一个想法,我改进了这个想法。

答案 2 :(得分:1)

你不能......但你可以通过在透明背景的输入上放置div来伪造它,并在该div上定义click函数。

$('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.');
});

Here's the working jsFiddle

答案 3 :(得分: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");
});​

DEMO: http://jsfiddle.net/q6u64/