【问题标题】:How to increment/append radio buttons with JQuery with unique id/name?如何使用具有唯一 ID/名称的 JQuery 增加/附加单选按钮?
【发布时间】:2018-01-14 20:50:02
【问题描述】:

我要做的是使用简单的“确认/拒绝”选项来增加/附加单选按钮。 从逻辑上讲,当我们添加或增加单选按钮时,单选按钮的 id 和名称会发生​​变化。

所以我想弄清楚的是:每当我们点击一​​个按钮时,它都会添加:

<H1>David's Attendance: <span>Confirmed</span></H1> 

带有确认和拒绝单选按钮,因此无论何时选择任一选项, 从“已确认”更改为“已拒绝”。那部分有效。

问题是每次生成元素时,所有跨度都会发生变化。我想要一种生成仅适用于生成的 H1“部分”的单选按钮的方法。这个想法是:你点击一个按钮来生成一个

<H1>David's Attendance: <span>Confirmed</span></H1> 

带有一个确认和拒绝单选按钮,这将改变那个跨度;再次点击按钮,它会生成另一个

<H1>David's Attendance: <span>Confirmed</span></H1> 

带有一个确认和拒绝单选按钮,它将改变那个跨度(而不是已经生成的所有两个)。

我知道我想说的很难理解,但这里是a visual example of JSFiddle that I got working.

感谢大家的帮助!

【问题讨论】:

    标签: javascript jquery html radio-button increment


    【解决方案1】:

    首先你应该注意你正在尝试做的事情,为元素分配动态标识符,是一种应该避免的反模式。

    要以更好的方式解决此问题,请使用类和 DOM 遍历来根据已知的 HTML 结构查找相关元素,从而使您的代码保持干燥。

    在您的特定情况下,您可以使用closest() 获取包含div,然后使用find() 获取其中的.attendance 元素,然后根据所选单选按钮设置文本。试试这个:

    $('.add_attr').click(function(e) {
      e.preventDefault();
      var newIndex = $('.attr_entry').length;
      $(".attr_entry:first").clone(true).removeClass('existent').insertAfter(".attr_entry:last").find('input[type="radio"]').prop('name', 'designator[' + newIndex + ']');
    });
    
    $('.remove_attr').click(function(e) {
      e.preventDefault();
      var $entry = $(this).closest('.attr_entry');
      if ($entry.hasClass('existent')) {
        alert('You can not remove the first attribute entry.');
      } else {
        $entry.remove();
      }
    });
    
    $('.radio').change(function() {
      var $attendance = $(this).closest('.attr_entry').find('.attendance');
      $attendance.text(this.value == '1' ? 'Confirmed' : 'Declined');
    });
    h1 {
      color: black;
      font-family: "Courier New", monospace;
      margin-left: -10px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="attr_entry existent row">
      <div class="half">
        <h1>David's Attendence: <span class="attendance">Confirmed</span></h1>
        <p>
          <a href="#" class="add_attr"><i class="fa fa-plus-circle"></i> Add Another Attribute</a>
          <a href="#" class="remove_attr"><i class="fa fa-minus-circle"></i> Remove</a>
        </p>
      </div>
      <div class="half">
        <label>
      <input type="radio" name="designator[0]" id="radio1" checked="checked" value="1" class="radio"> Confirm
    </label>
        <label>
      <input type="radio" name="designator[0]" value="0" class="radio"> Decline
    </label>
      </div>
    </div>

    【讨论】:

    • 感谢@Rory(似乎无法直接回复评论),为您提供解决方案!你熟悉 Node JS 吗?因为我试图在 Node JS 中附加一个文件,该文件会在每次提交表单时增加单选按钮。
    • 完成!再次感谢您的解决方案,这对我帮助很大,祝您有美好的一天!
    猜你喜欢
    • 2016-05-22
    • 2021-08-05
    • 2019-03-15
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 2013-11-03
    • 2011-05-17
    • 2015-05-08
    相关资源
    最近更新 更多