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触发某些操作?
重新阅读了来自 JoãoSilva
的有关使用 readonly
的评论。您可以使用它并将其与点击事件中的某些逻辑连接起来。
使用readonly
会给您提供与disabled
相同的禁用外观,但它仍然允许您单击它。
像这样使用 readonly:
<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.
});
readonly
应该指定为没有值或者值为 readonly
,即 readonly="readonly"
,而不是 true
。 - Barmarattr
,因为我不知道你使用的是哪个版本的jQuery。prop
是在1.6中添加的,所以如果你至少使用了1.6,相关的代码行可以更改为var isReadOnly = !$(this).prop("readonly");
,代码仍然可以正常工作。 - Nope您无法在所有浏览器中可靠地捕获点击事件。最好的选择是在上方放置一个透明元素来捕获点击。
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 上定义点击函数来模拟实现。
$('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.');
});
我经常这样做,以防止人们更改已提交到数据库的复选框。但是,如果您想要更改它或至少看到单击..那么我只需将输入包装在标签元素中并检查子输入。
HTML:
<label class="checkbox-label">
<input class="input-checkbox" type="checkbox" name="declared" disabled checked>
</label>
JQuery:
$('.checkbox-label').on(function (e) {
e.stopPropagation();
let checkBox = $(this).find('.input-checkbox');
// if checkbox is disabled, do something
if (checkBox.prop('disabled')) {
// I usually put some enter password to confirm change... but I know you want to just show a click
console.log('click')
} else {
// your checkbox should act as normal
console.log('click')
}
})
我认为没有其他选择,只能在复选框上添加 <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");
});
readonly="true"
会使控件变灰,但用户仍然可以在Chrome中勾选/取消勾选它。 - Nope