使用 jQuery 检查单选按钮不会触发单选按钮的 onclick 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19546021/
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
Checking radio button with jQuery doesn't trigger radio's onclick event
提问by DiegoDD
I have a pair of radios, to which I assign a function using bind(), on the pages .ready event. then, on the same ready event, I check for another input's value, and if it's value is "1" I preselect the second radio button when the page loads. here is a snippet.
我有一对收音机,我在页面 .ready 事件上使用 bind() 为其分配了一个函数。然后,在同一个就绪事件中,我检查另一个输入的值,如果它的值为“1”,则在页面加载时预选第二个单选按钮。这是一个片段。
<input type="radio" name="fpago" id="fpago1" value="1" />one
<input type="radio" name="fpago" id="fpago2" value="2" />two
...
...
$(document).ready(function() {
$("#myspan").hide();
$("#fpago1, #fpago2").bind('change click',function(){
togglePlazo();
});
//initial condition to preselect radio #2
grupo = $("#id_grupo").val();
if(grupo != '0'){
$("#fpago2").attr('checked', true); //checks the radio, but doesn't trigger function
}
});
...
...
--> see herefor a more complete code
-->更完整的代码请看这里
The problem is that, the radio does get checked if the condition is met, BUT the bound function togglePlazo()
doesn't trigger...
问题是,如果条件满足,无线电确实会得到检查,但绑定函数togglePlazo()
不会触发......
If later I manually click the radio buttons, the function does get triggered, and the span toggles. It is only on the initial "check" made with jQuery, where the function does not trigger despite the radio getting changed.
如果稍后我手动单击单选按钮,该功能会被触发,并且跨度会切换。它仅在使用 jQuery 进行的初始“检查”中进行,尽管无线电已更改,但该功能不会触发。
I don't know what I'm missing, maybe I should bind more events other than change or click... I just can't find what I am doing wrong.
我不知道我错过了什么,也许我应该绑定更多的事件而不是更改或点击......我只是找不到我做错了什么。
NOTE: I am using jQuery 1.4.2, but the fiddle is set to use 1.6.4 (it doesn't have 1.4.2 as an option)
注意:我使用的是 jQuery 1.4.2,但小提琴设置为使用 1.6.4(它没有 1.4.2 作为选项)
回答by adamb
Just trigger the click event when you set the checked
attribute.
设置checked
属性时触发点击事件即可。
$("#fpago2").attr('checked', true).trigger('click');
Changing an attribute on the element doesn't fire a changed event... Neither by the native setAttribute or using jQuery's attr.
更改元素上的属性不会触发已更改的事件……无论是通过本机 setAttribute 还是使用 jQuery 的 attr。