克隆和更新属性

时间:2011-05-04 17:20:34

标签: javascript jquery html forms

我的第一个问题是,但在过去的一年中,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>

(注意:这是我正在尝试的高度缩小的版本,如果我适当缩放它,请原谅我。)

谢谢, 马特

1 个答案:

答案 0 :(得分: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'));
});

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

相关问题