克隆和更新属性(Clone and update attributes)

2019-10-16 13:07发布

我在这里的第一个问题,但计算器一直是我的一个高度重视资源在过去的一年。

我建立一种高级形式。 我需要的用户必须添加亚群的能力。 我使用的jQuery(1.5.1 - 我想我应该更新。)克隆的对象。 我的问题是我还需要它来更新属性。

我在想,如果存在要做到这一点,我无法找到,或者我应该写这个自己的一种方式。 这似乎是一件容易的事,使属性的数量,并添加一个。

我所提供的一些代码,一个简短的例子。

<form class="clause">
  <input type="radio" id="radio-1" name="radio" checked="checked" />
    <label for="radio-1">And</label>
  <input type="radio" id="radio-2" name="radio" />
    <label for="radio-2">Or</label>
  <input type="radio" id="radio-3" name="radio" />
    <label for="radio-3">Not</label>
 <button class="ag">Add SubGroup</button>
</form>


<!-- yes, this is in an external file -->
<script type="text/javascript">

$(function() {
  $('.ag').click(function() {
$('.clause').clone(true).insertAfter($('.clause:last'));
 });
</script>

这种重复,相当不错,表格,之后将自身插入一个副本。

显然,不更新单选按钮的属性。 因此,如果一个单选按钮是在一个子组选中它是适用于他们。 我不希望这种事情发生。

请问这个功能存在吗? 这是如果没有,则没有问题,但我想在这个项目中没有任何重塑车轮。

编辑:

为了说明这个问题,更好地我在下面提供更多的代码。 详图我想要的结果

<form class="clause">
      <input type="radio" id="radio-1" name="radio" checked="checked" />
        <label for="radio-1">And</label>
      <input type="radio" id="radio-2" name="radio" />
        <label for="radio-2">Or</label>
      <input type="radio" id="radio-3" name="radio" />
        <label for="radio-3">Not</label>
      <button class="ag">Add SubGroup</button>
   </form>
   <form class="clause">
      <input type="radio" id="radio-4" name="radio" checked="checked" />
        <label for="radio-4">And</label>
      <input type="radio" id="radio-5" name="radio" />
        <label for="radio-5">Or</label>
      <input type="radio" id="radio-6" name="radio" />
        <label for="radio-6">Not</label>
      <button class="ag">Add SubGroup</button>
   </form>

   <!-- yes, this is in an external file -->
   <script type="text/javascript">
    $(function() {
      $('.ag').click(function() {
    $('.clause:last').clone(true).insertAfter($('.clause:last'));
     });
    </script>

(注意:这是我在尝试的一个高度精简版本,并原谅我,如果我适当缩放它。)

谢谢,马特

Answer 1:

$('.ag').click(function() {
  // I would advise using :last so you don't exponentially grow your form
  var clone = $('.clause:last').clone(true);

  // now find all the radios and reset them
  $('input[type=radio]',clone).removeAttr('checked');

  // now add it
  clone.insertAfter($('.clause:last'));
});

使用选择(范围)和搜索的第二个参数的克隆中重置领域追加前/属性。



文章来源: Clone and update attributes