【问题标题】:Radio Button Change Event Doesn't Fire Properly单选按钮更改事件未正确触发
【发布时间】:2017-07-02 20:58:48
【问题描述】:

应该相当简单。我正在尝试实现一个单选按钮组。当单击一个单选按钮时,它会在下面附加一个文本“测试”,当单击另一个单选按钮时,第一个单选按钮上的文本将消失,第二个单选按钮将附加文本。此外,还有一个动态添加单选按钮的按钮,并且将更改事件添加到该单选按钮中。以下是我的代码:

此代码的问题是,当我单击第二个单选按钮时,第一个单选按钮文本不会消失,而当我检查第三个单选按钮时,第二个和第一个单选按钮文本不会消失。

我该如何解决?

function add() {

  var cat_name = $('input.text').val();
  $('div.radioGroup').append('<div><div><input type="radio" name="cat" value="' + cat_name + '"/> ' + cat_name + '<br /></div></div>');

  var inputDOM = $('input[value="' + cat_name + '"]');

  $('input:radio[name="cat"]').on('change', function() {
    // alert(cat_name);

    console.log("");
    console.log(cat_name);
    console.log(cat_name + " ischecked is " + $('input[value="' + cat_name + '"]').is(":checked"));

    if ($('input[value="' + cat_name + '"]').is(":checked")) {
      inputDOM.parent().after("<span style='margin-left:5em'>test</span><br>");
      // alert("yes is working");
    } else {
      // alert("uncheck is working!");
      console.log("uncheck is working");
      inputDOM.parent().nextAll().remove();

    }
  });


  $('input.text').val('');


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="radioGroup">

</div>
<input type="text" name="text" class="text">
<button onclick="add()">Add</button>

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

移动

$('input:radio[name="cat"]').on('change', function() { 

在 add() 之外并使用委托:

$('div.radioGroup').on("change",'radio[name="cat"]',function() {

可能是这样的。来不及猜测你真正想要什么

function add() {

  var cat_name = $('input.text').val();
  $('div.radioGroup').append('<div><div><input type="radio" name="cat" value="' + cat_name + '"/> ' + cat_name + '<br /></div></div>');
  $('input.text').val('');
}

$('div.radioGroup').on('change', 'input:radio[name="cat"]',function() {
  var cat_name=this.name, inputDOM = $('input[value="' + cat_name + '"]');
  console.log("");
  console.log(cat_name);
  console.log(cat_name + " ischecked is " + $('input[value="' + cat_name + '"]').is(":checked"));

  if ($('input[value="' + cat_name + '"]').is(":checked")) {
    inputDOM.parent().after("<span style='margin-left:5em'>test</span><br>");
    // alert("yes is working");
  } else {
    // alert("uncheck is working!");
    console.log("uncheck is working");
    inputDOM.parent().nextAll().remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="radioGroup">

</div>
<input type="text" name="text" class="text">
<button onclick="add()">Add</button>

【讨论】:

  • cat_name 应该被命名为 value_name。它是单选按钮的值。选择器以值区分。此外,它不起作用。现在文字甚至不再消失,一切都在不断堆积。当您单击其他单选按钮时,我想要它,第一个选择的按钮附加文本消失。
  • 我不明白。您不能取消选中收音机 - 您可以取消选中复选框。你能显示一些点击前后的图片吗?我想删除 inputDOM 并使用 $(this) 作为遍历锚
猜你喜欢
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 2013-07-19
  • 1970-01-01
相关资源
最近更新 更多