js/jQuery:
$('input[type=checkbox]').click(function(){
// Does not fire if I click a <input type="checkbox" disabled="disabled" />
});
当有人单击禁用的复选框时,如何在 jQuery 中发生某些事情?
js/jQuery:
$('input[type=checkbox]').click(function(){
// Does not fire if I click a <input type="checkbox" disabled="disabled" />
});
当有人单击禁用的复选框时,如何在 jQuery 中发生某些事情?
再次阅读有关使用readonly
from的评论JoãoSilva
。您可以使用它并将其与点击事件中的一些逻辑联系起来。
Usingreadonly
给你一个禁用的外观,就像它一样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.
});
您将无法在所有浏览器中可靠地捕获点击事件。最好的办法是在上方放置一个透明元素来捕捉点击。
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 :)
});
注意:这是我改进的这个问题的一个想法。
你不能......但你可以通过在输入上放置一个具有透明背景的 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.');
});
我看不到在复选框上添加<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/