我在名为 item
的 Div 中有以下 html 标记,我想选择所有元素(在嵌套 div 内)并清除值。如下面给定的 Jquery 所示,我已成功使用.children().each()
访问每个 Div 中的元素。但问题是 .children().each()
从父 div 一次向下一级,所以我用多个 .children()< 重复相同的代码块
要访问嵌套 Div 内的元素,任何人都可以建议我一种方法来执行此操作,而无需重复 N 个嵌套 div 的代码。
html 标记
<div class="item">
<input type="hidden" value="1234" name="testVal">
<div class="form-group" id="c1">
<div class="controls ">
<input type="text" value="Results" name="s1" maxlength="255" id="id2">
</div>
</div>
<div class="form-group" id="id4">
<input type="text" value="Results" name="s12" maxlength="255" id="id225">
<div class="form-group" id="id41">
<input type="text" value="Results" name="s12" maxlength="255" id="5">
<div class="form-group" id="id42">
<input type="text" value="Results" name="s12" maxlength="255" id="5">
<div class="form-group" id="id43">
<input type="text" value="Results" name="s12" maxlength="255" id="id224">
</div>
</div>
</div>
</div>
</div>
我的 Qjuery 脚本
var row = $(".item:first").clone(false).get(0);
$(row).children().each(function () {
updateElementIndex(this, prefix, formCount);
if ($(this).attr('type') == 'text') {
$(this).val('');
}
if ($(this).attr('type') == 'hidden' && ($(this).attr('name') != 'csrfmiddlewaretoken')) {
$(this).val('');
}
if ($(this).attr('type') == 'file') {
$(this).val('');
}
if ($(this).attr('type') == 'checkbox') {
$(this).attr('checked', false);
}
$(this).remove('a');
});
// Relabel or rename all the relevant bits
$(row).children().children().each(function () {
updateElementIndex(this, prefix, formCount)
if ($(this).attr('type') == 'text') {
$(this).val('');
}
if ($(this).attr('type') == 'hidden' && ($(this).attr('name') != 'csrfmiddlewaretoken')) {
$(this).val('');
}
if ($(this).attr('type') == 'file') {
$(this).val('');
}
if ($(this).attr('type') == 'checkbox') {
$(this).attr('checked', false);
}
$(this).remove('a');
});
最佳答案
似乎这样的事情就能解决问题。当然,您要更具体地说明您选择的项目。
$('.item').find('input').val('');
关于javascript - 使用 JQuery 选择嵌套 Div 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19771830/