jQuery 在jquery中选择并触发单选按钮的点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17980406/
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 20:18:53  来源:igfitidea点击:

Select and trigger click event of a radio button in jquery

javascriptjqueryjquery-ui

提问by user2569524

Upon document load, am trying to trigger the click event of the first radio button.... but the click event is not triggered.Also, tried 'change' instead of click ...but its the same result.

在文档加载时,我试图触发第一个单选按钮的点击事件......但点击事件是not triggered.Also,尝试“更改”而不是点击......但其结果相同。

$(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");

    });

});

Please follow the below link to the question

请按照以下链接回答问题

Example: http://jsbin.com/ezesaw/1/edit

示例:http: //jsbin.com/ezesaw/1/edit

Please help me out in getting this right. Thanks!

请帮我解决这个问题。谢谢!

回答by Sushanth --

You are triggering the event before the event is even bound.

甚至在事件绑定之前触发事件

Just move the triggeringof the event to after attaching the event.

triggering附加事件后,只需将事件的移动到 即可。

$(document).ready(function() {
  $("#checkbox_div input:radio").click(function() {

    alert("clicked");

   });

  $("input:radio:first").prop("checked", true).trigger("click");

});

Check Fiddle

检查小提琴

回答by Hyman

Switch the order of the code: You're calling the click event before it is attached.

切换代码的​​顺序:在附加之前调用 click 事件。

$(document).ready(function() {
      $("#checkbox_div input:radio").click(function() {

           alert("clicked");

      });

      $("input:radio:first").prop("checked", true).trigger("click");

});

回答by inMILD

My solution is a bit different:

我的解决方案有点不同:

$( 'input[name="your_radio_input_name"]:radio:first' ).click();

回答by Manoj Datt

In my case i had to load images on radio button click, I just uses the regular onclickevent and it worked for me.

在我的情况下,我必须在单击单选按钮时加载图像,我只使用常规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>

回答by Pankaj sharma

$("#radio1").attr('checked', true).trigger('click');