【问题标题】:Select and trigger click event of a radio button in jquery在jquery中选择并触发单选按钮的单击事件
【发布时间】:2013-07-31 20:32:43
【问题描述】:
在加载文档时,我试图触发第一个单选按钮的单击事件....但单击事件是not triggered。此外,尝试“更改”而不是单击...但结果相同。
$(document).ready(function() {
//$("#checkbox_div input:radio").click(function() {
$("input:radio:first").prop("checked", true).trigger("click");
//});
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
});
请点击以下链接提问
示例:
http://jsbin.com/ezesaw/1/edit
请帮助我解决这个问题。
谢谢!
【问题讨论】:
标签:
javascript
jquery
jquery-ui
【解决方案1】:
您正在触发事件甚至在事件绑定之前。
只需将事件的triggering 移动到附加事件后即可。
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
Check Fiddle
【解决方案2】:
切换代码顺序:你在点击事件之前调用它。
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
【解决方案3】:
我的解决方案有点不同:
$( 'input[name="your_radio_input_name"]:radio:first' ).click();
【解决方案4】:
在我的情况下,我必须在单击单选按钮时加载图像,
我只是使用常规的onclick 事件,它对我有用。
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
【解决方案5】:
$("#radio1").attr('checked', true).trigger('click');