Jquery儿童的元素

时间:2016-04-25 02:55:02

标签: javascript jquery

$(parentQuestion.children('.choice_class:last'));
<div class='parentquestion'> .....
<div class="choice_class">
            <div class="form-group">
                <label class="control-label col-md-3 col-sm-3 col-xs-12"><span class="choice-no">Option 1</span><span class="required">*</span>
                </label>
                <div class="col-md-6 col-sm-6 col-xs-12">
                    <input type="text" required="required" class="form-control col-md-7 col-xs-12">
                </div>
                <a href="javascript: void(0);" onclick="addOption(this)" class="btn btn-danger"><span class="glyphicon glyphicon-plus"></span>Add Choice</a>
            </div>
        </div>

在addOption函数中,使用this变量,我找到了父对象,并在最后一个.choice_class下添加了另一个选项。

添加第二个选项时,我需要将选项1更改为选项2.

完整的功能是

function addOption(that) {
      $(that).parent().parent().after($('.choice_class_sample .choice_class').clone());

      var parentQuestion = $(that).parent().parent().parent();
      var lastChoice = parentQuestion.children('.choice_class:last');

      $(parentQuestion.children('.choice_class:last-child .choice-no')).html(parentQuestion.children('.choice_class').length);
      $(that).remove();
  }

但是在选择孩子后我无法再选择更多。

1 个答案:

答案 0 :(得分:2)

我可以修改你的代码“让它工作”,但是你的方式有点不正统 - 即在复制之前使用clone复制现有元素。

如果您要在DOM中表示JavaScript数据结构(如数组),并希望保持它们同步,那么使用模板系统会好得多。由于您使用的是jQuery,jQuery Template plugin似乎不错。从浏览README开始,它会让你的东西变得如此简单:

<script type="text/html" id="template">
  <div>
    <div>
      <label>
        <span>Option <span data-content="id"></span></span>
        <span class="required">*</span>
      </label>

      <div>
        <input type="text" required="required">
      </div>

      <a href="#" class="add-choice-button"><span class="glyphicon glyphicon-plus"></span> Add Choice</a>
    </div>
  </div>
</script>

然后,在你的JavaScript中,你会有类似的东西:

var options = [ { id: 1 } ]

parentQuestion.loadTemplate("#template", questions)

$('.add-choice-button').on('click', function () {
  options.push({
    id: options.length + 1  
  })

  parentQuestion.loadTemplate('#template', options)
})

更清洁。最重要的是,它避免了在JS中使用丑陋的命令式DOM操作。