首页 > 解决方案 > 输入类型“收音机”jQuery上的单击事件

问题描述

无法将事件分配给单选按钮。我用谷歌搜索了这个问题,有很多不同的解决方案,但没有任何帮助。

我尝试的最后一个解决方案是:

$(document).ready(function() {
  $("#monthly input[name=pricing-1]").click(function() {
    console.log("Test");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-round btn-outline-primary w-150 active">
        <input id="monthly" name="pricing-1" value="monthly" autocomplete="off" checked="" type="radio"> Monthly
      </label>
</div>

但是当我单击按钮时没有任何反应。怎么了?

标签: javascriptjquery

解决方案


问题:

主要问题来自选择器#monthly input[name=pricing-1],它将搜索名称pricing-1为 id 的元素的子元素的输入monthly

解决方案:

您必须使用$("input[name=pricing-1]")or$("#monthly")作为选择器,因为两者都引用相同的元素:

$(document).ready(function() {
  $("#monthly").click(function() {
    console.log("Test 1");
  });
  $("input[name=pricing-1]").click(function() {
    console.log("Test 2");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-round btn-outline-primary w-150 active">
        <input id="monthly" name="pricing-1" value="monthly" autocomplete="off" checked="" type="radio"> Monthly
      </label>
</div>


推荐阅读