我编写了这段 javascript/jQuery 片段来更改复选框。 http://jsfiddle.net/johnhoffman/crF93/
Javascript
$(function() {
$("a").click(function() {
if ($("input[type='checkbox']").attr('checked') == "checked")
$("input[type='checkbox']").removeAttr('checked');
else
$("input[type='checkbox']").attr('checked', 'checked');
return false;
});
$("input[type='checkbox']").change(function(){
console.log("Checkbox changed.");
});
});
HTML
<input type="checkbox" />
<a href="#">Change CheckBox</a>
有趣的是,单击链接会更改文本框,但不会触发调用在 Chrome Web 开发人员控制台中记录消息的函数的表单更改事件。为什么?我怎样才能让它做到这一点?
最佳答案
您需要触发更改事件,.trigger('change')
,以便该事件知道发生了更改。
来自http://api.jquery.com/change/ :
Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
This method is a shortcut for
.on( "change", handler )
in the first two variations, and.trigger( "change" )
in the third.The
change
event is sent to an element when its value changes. This event is limited to<input>
elements,<textarea>
boxes and<select>
elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
演示:
使用链接:http://jsfiddle.net/nPkPw/5/
即$("input[type='checkbox']").trigger('change').attr('checked', 'checked');
关于javascript - 为什么动态更改复选框不会触发表单更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10159214/