(jQuery 1.4.4)我有一个带有.change()监听器的复选框,当用户单击复选框时,该监听器工作正常,但现在我还需要在我以编程方式更改jQuery中的复选框时使用.attr( '已检查','已检查').我非常乐意使用其他方法来完成这项工作.谢谢.
$('#foo').attr('checked', 'checked'); // programmatically change the checkbox to checked, this checks the box alright
$('#foo').change( function() {
// this works when user checks the box but not when the above code runs
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*att 23
如果你使用jQuery> 1.6,你可以通过定义一个attrHook;
jQuery.attrHooks.checked = {
set: function (el, value) {
if (el.checked !== value) {
el.checked = value;
$(el).trigger('change');
}
}
};
Run Code Online (Sandbox Code Playgroud)
正如评论中所指出的,如果新值与旧值相同,则if避免change触发事件.
...虽然你真的应该使用prop()它,所以它应该是;
jQuery.propHooks.checked = {
set: function (el, value) {
if (el.checked !== value) {
el.checked = value;
$(el).trigger('change');
}
}
};
Run Code Online (Sandbox Code Playgroud)
你可以看到这个在这里工作; http://jsfiddle.net/2nKPY/
对于jQuery <1.6(或者如果你不想添加一个propHook),你可以做的最好是覆盖attr()方法(或升级:));
(function () {
var existingAttr = jQuery.fn.attr;
jQuery.fn.attr = function (attr) {
var result = existingAttr.apply(this, arguments);
if (result instanceof jQuery && attr == "checked") { // If we're dealing with a check-set operation.
result.trigger('change');
}
return this;
};
}());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10400 次 |
| 最近记录: |