克隆和更新属性

Clone and update attributes

本文关键字:属性 更新      更新时间:2023-09-26

我的第一个问题,但是stackoverflow在过去的一年中对我来说是一个非常有价值的资源。

我正在构建一个高级表单。我需要用户有能力添加子组。我使用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>

(注意:这是我所尝试的一个高度缩小的版本,如果我适当地缩小了,请原谅我。)

谢谢,马特

$('.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'));
});

使用选择器的第二个参数(Scope)并在克隆中搜索,在附加它之前重置字段/属性。