If you're using jQuery > 1.6, you can do this quite smartly by defining a attrHook
;
jQuery.attrHooks.checked = {
set: function (el, value) {
if (el.checked !== value) {
el.checked = value;
$(el).trigger('change');
}
}
};
As pointed out in the comments, the if
avoids a change
event triggering if the new value is the same as the old value.
... Although really you should be using prop()
anyway, so it should be;
jQuery.propHooks.checked = {
set: function (el, value) {
if (el.checked !== value) {
el.checked = value;
$(el).trigger('change');
}
}
};
You can see this working here; http://jsfiddle.net/2nKPY/
For jQuery < 1.6 (or if you don't fancy adding a propHook
) the best you can do is override the attr()
method (or upgrade :));
(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;
};
}());
You can see this in operation here
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…