jQuery 复选框事件处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3442322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:27:53  来源:igfitidea点击:

jQuery checkbox event handling

jqueryhtmlcheckbox

提问by aeq

I have the following:

我有以下几点:

<form id="myform">
   <input type="checkbox" name="check1" value="check1">
   <input type="checkbox" name="check2" value="check2">
</form>

How do I use jQuery to capture anycheck event occuring in myformand tell which checkbox was toggled (and know if it was toggled on or off)?

如何使用 jQuery 捕获发生的任何检查事件myform并判断哪个复选框被切换(并知道它是打开还是关闭)?

回答by Darin Dimitrov

$('#myform :checkbox').change(function() {
    // this will contain a reference to the checkbox   
    if (this.checked) {
        // the checkbox is now checked 
    } else {
        // the checkbox is now no longer checked
    }
});

回答by Anurag

Use the change event.

使用更改事件。

$('#myform :checkbox').change(function() {
    // this represents the checkbox that was checked
    // do something with it
});

回答by Gone Coding

There are several useful answers, but none seem to cover all the latestoptions. To that end all my examples also cater for the presence of matching labelelements and also allow you to dynamically add checkboxes and see the results in a side-panel (by redirecting console.log).

有几个有用的答案,但似乎没有一个涵盖所有最新选项。为此,我的所有示例还满足匹配label元素的存在,并允许您动态添加复选框并在侧面板中查看结果(通过重定向console.log)。

  • Listening for clickevents on checkboxesis nota good idea as that will not allow for keyboard toggling or for changes made where a matching labelelement was clicked. Always listen for the changeevent.

  • Use the jQuery :checkboxpseudo-selector, rather than input[type=checkbox]. :checkboxis shorter and more readable.

  • Use is()with the jQuery :checkedpseudo-selector to test for whether a checkbox is checked. This is guaranteed to work across all browsers.

  • 监听click的事件checkboxes不是一个好主意,因为这将不允许键盘肘或做了匹配,其中改变label被点击的元素。始终监听change事件。

  • 使用 jQuery:checkbox伪选择器,而不是input[type=checkbox]. :checkbox更短,更易读。

  • is()与 jQuery:checked伪选择器一起使用来测试复选框是否被选中。这保证适用于所有浏览器。

Basic event handler attached to existing elements:

附加到现有元素的基本事件处理程序:

$('#myform :checkbox').change(function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle:http://jsfiddle.net/TrueBlueAussie/u8bcggfL/2/

JSFiddle:http : //jsfiddle.net/TrueBlueAussie/u8bcggfL/2/

Notes:

笔记:

  • Uses the :checkboxselector, which is preferable to using input[type=checkbox]
  • This connects onlyto matching elements that exist at the time the event was registered.
  • 使用:checkbox选择器,这比使用更可取input[type=checkbox]
  • 连接到注册事件时存在的匹配元素。


Delegated event handler attached to ancestor element:

附加到祖先元素的委托事件处理程序:

Delegated event handlers are designed for situations where the elements may not yet exist (dynamically loaded or created) and is veryuseful. They delegateresponsibility to an ancestor element (hence the term).

委托事件处理程序专为元素可能尚不存在(动态加载或创建)的情况而设计,非常有用。它们责任委托给祖先元素(因此称为术语)。

$('#myform').on('change', ':checkbox', function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle:http://jsfiddle.net/TrueBlueAussie/u8bcggfL/4/

JSFiddle:http : //jsfiddle.net/TrueBlueAussie/u8bcggfL/4/

Notes:

笔记:

  • This works by listening for events (in this case change) to bubble up to a non-changing ancestor element (in this case #myform).
  • It thenapplies the jQuery selector (':checkbox'in this case) to only the elements in the bubble chain.
  • It thenapplies the event handler function to only those matching elements that caused the event.
  • Use documentas the default to connect the delegated event handler, if nothing else is closer/convenient.
  • Do not use bodyto attach delegated events as it has a bug (to do with styling) that can stop it getting mouse events.
  • 这通过侦听事件(在这种情况下change)冒泡到一个不变的祖先元素(在这种情况下#myform)来工作。
  • 然后它仅将 jQuery 选择器(':checkbox'在本例中)应用于气泡链中的元素。
  • 然后它只将事件处理函数应用于那些导致事件的匹配元素。
  • 使用document作为默认连接委托事件处理程序,如果没有别的更接近/方便。
  • 不要使用body附加委托事件,因为它有一个错误(与样式有关)可以阻止它获取鼠标事件。

The upshot of delegated handlers is that the matching elements only need to exist at event timeand not when the event handler was registered. This allows for dynamically added content to generate the events.

委托处理程序的结果是匹配元素只需要在事件时间存在而不是在事件处理程序注册时存在。这允许动态添加的内容来生成事件。

Q: Is it slower?

问:是不是比较慢?

A:So long as the events are at user-interaction speeds, you do not need to worry about the negligibledifference in speed between a delegated event handler and a directly connected handler. The benefits of delegation far outweigh any minor downside. Delegated event handlers are actually faster to registeras they typically connect to a single matching element.

答:只要事件处于用户交互速度,您就不必担心委托事件处理程序和直接连接的处理程序之间的速度差异可以忽略不计。授权的好处远远超过任何小的缺点。委托事件处理程序实际上注册速度更快,因为它们通常连接到单个匹配元素。



Why doesn't prop('checked', true)fire the changeevent?

为什么不prop('checked', true)触发change事件?

This is actually by design. If it did fire the event you would easily get into a situation of endless updates. Instead, after changing the checked property, send a change event to the same element using trigger(not triggerHandler):

这实际上是设计使然。如果它确实触发了事件,您将很容易陷入无休止更新的境地。相反,在更改 checked 属性后,使用trigger(not triggerHandler)向同一元素发送更改事件:

e.g. without triggerno event occurs

例如trigger没有事件发生

$cb.prop('checked', !$cb.prop('checked'));

JSFiddle:http://jsfiddle.net/TrueBlueAussie/u8bcggfL/5/

JSFiddle:http : //jsfiddle.net/TrueBlueAussie/u8bcggfL/5/

e.g. with triggerthe normal change event is caught

例如,trigger捕获正常的更改事件

$cb.prop('checked', !$cb.prop('checked')).trigger('change');

JSFiddle:http://jsfiddle.net/TrueBlueAussie/u8bcggfL/6/

JSFiddle:http : //jsfiddle.net/TrueBlueAussie/u8bcggfL/6/

Notes:

笔记:

  • Do not use triggerHandleras was suggested by one user, as it will not bubble events to a delegatedevent handler.
  • 不要triggerHandler按照一位用户的建议使用,因为它不会将事件冒泡到委托的事件处理程序。

JSFiddle:http://jsfiddle.net/TrueBlueAussie/u8bcggfL/8/

JSFiddle:http : //jsfiddle.net/TrueBlueAussie/u8bcggfL/8/

although it willwork for an event handler directly connectedto the element:

虽然它为事件处理工作直接连接的元素:

JSFiddle:http://jsfiddle.net/TrueBlueAussie/u8bcggfL/9/

JSFiddle:http : //jsfiddle.net/TrueBlueAussie/u8bcggfL/9/

Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

用 .triggerHandler() 触发的事件不会在 DOM 层次结构中冒泡;如果它们不是由目标元素直接处理,则它们什么都不做。

Reference: http://api.jquery.com/triggerhandler/

参考:http: //api.jquery.com/triggerhandler/

If anyone has additional features they feel are not covered by this, please do suggest additions.

如果有人有他们认为未涵盖的其他功能,请提出添加建议

回答by Allen Hamilton

Using the new 'on' method in jQuery (1.7): http://api.jquery.com/on/

在 jQuery (1.7) 中使用新的“on”方法:http: //api.jquery.com/on/

    $('#myform').on('change', 'input[type=checkbox]', function(e) {
        console.log(this.name+' '+this.value+' '+this.checked);

    });
  • the event handler will live on
  • will capture if the checkbox was changed by keyboard, not just click
  • 事件处理程序将继续存在
  • 将捕获是否通过键盘更改了复选框,而不仅仅是单击

回答by Chase Sandmann

Acknowledging the fact that the asker specifically requested jQuery and that the answer selected is correct, it should be noted that this problem doesn't actually needjQuery per say. If one desires to solve this problem without it, one can simply set the onClickattribute of the checkboxes that he or she wants to add additional functionality to, like so:

承认提问者特别请求 jQuery 并且选择的答案是正确的这一事实,应该注意这个问题实际上并不需要jQuery。如果希望在没有它的情况下解决这个问题,可以简单地设置onClick他或她想要添加附加功能的复选框的属性,如下所示:

HTML:

HTML:

<form id="myform">
  <input type="checkbox" name="check1" value="check1" onClick="cbChanged(this);">
  <input type="checkbox" name="check2" value="check2" onClick="cbChanged(this);">
</form>

javascript:

javascript:

function cbChanged(checkboxElem) {
  if (checkboxElem.checked) {
    // Do something special
  } else {
    // Do something else
  }
}

Fiddle: http://jsfiddle.net/Y9f66/1/

小提琴:http: //jsfiddle.net/Y9f66/1/

回答by Thinker

$('#myform input:checkbox').click(
 function(e){
   alert($(this).is(':checked'))
 }
)

回答by Somwang Souksavatd

I have try the code from first answer, it not working but I have play around and this work for me

我已经尝试了第一个答案中的代码,它不起作用,但我已经玩过了,这对我有用

$('#vip').change(function(){
    if ($(this).is(':checked')) {
        alert('checked');
    } else {
        alert('uncheck');
    }
});