为什么动态更改复选框不会触发表单更改事件? [英] Why does dynamically changing a checkbox not trigger a form change event?

查看:160
本文介绍了为什么动态更改复选框不会触发表单更改事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个javascript / jQuery片段来更改复选框。
http://jsfiddle.net/johnhoffman/crF93/

I wrote this snippet of javascript/jQuery to change a check box. http://jsfiddle.net/johnhoffman/crF93/

Javascript

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 Developer Console中记录消息的功能。为什么?我如何做到这一点?

Interestingly, clicking the link alters the text box, but does not trigger the form change event that calls the function that logs a message in Chrome Web Developer Console. Why? How do I make it do that?

推荐答案

您需要触发更改事件, .trigger( '更改'),以便事件知道发生了更改。

You need to trigger the change event, .trigger('change'), so that event knows that a change took place.

来自 http://api.jquery.com/change/


描述:将事件处理程序绑定到更改JavaScript事件,或在元素上触发该事件。

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

此方法是前两个版本中 .on(更改,处理程序)的快捷方式,以及 .trigger(更改)在第三个。

This method is a shortcut for .on( "change", handler ) in the first two variations, and .trigger( "change" ) in the third.

更改事件在其值发生变化时发送给元素。此活动仅限于< input> 元素,< textarea> 框和< ;选择> 元素。对于选择框,复选框和单选按钮,当用户使用鼠标进行选择时会立即触发事件,但对于其他元素类型,事件将延迟到元素失去焦点。

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/

ie $(input [type ='checkbox'])。触发器('更改')。attr('checked','checked');

这篇关于为什么动态更改复选框不会触发表单更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆