gpt4 book ai didi

javascript - Jquery Children的子元素

转载 作者:行者123 更新时间:2023-12-02 14:43:18 25 4
gpt4 key购买 nike

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

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

最佳答案

我可以修改您的代码以“使其工作”,但您的处理方式有点非正统 - 即,在复制现有元素之前使用 clone 来复制它。

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

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

关于javascript - Jquery Children的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com