javascript - 为什么动态更改复选框不会触发表单更改事件?

标签 javascript jquery

我编写了这段 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/3/

使用链接:http://jsfiddle.net/nPkPw/5/
$("input[type='checkbox']").trigger('change').attr('checked', 'checked');

关于javascript - 为什么动态更改复选框不会触发表单更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10159214/

相关文章:

javascript - 独立为同一类的元素设置动画

javascript - 响应式下拉导航问题

jquery - 更改 Eclipse 设置以忽略特定文件上的错误

javascript - 使用 CSS/border-radius 遮蔽图像

javascript - 一行 if else 语句中有什么问题

javascript - 查找具有特定类的所有下一个元素

javascript - 将事件监听器附加到 DOM,而不是污染全局命名空间

javascript - Fullcalendar:无法调整使用范围 [] 的重复事件的大小

javascript - Bootstrap 模式中的 Summer Note 问题

javascript图像调整窗口大小