Jquery Children's child element

Jquery Children's child element

本文关键字:child element Children Jquery      更新时间:2023-09-26
$(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();
  }

但是在选择孩子之后,我无法进一步选择更多。

我可以修改您的代码以"使其工作",但是您执行此操作的方式有点非正统 - 即在复制之前使用clone复制现有元素。

如果你打算在DOM中表示JavaScript数据结构(如数组),并希望使它们保持同步,那么使用模板系统会好得多。由于您使用的是jQuery,因此jQuery模板插件看起来不错。通过浏览自述文件,它会让你的东西像这样简单:

<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操作。