javascript - 使用 JQuery 选择嵌套 Div 中的元素

标签 javascript jquery jquery-selectors

我在名为 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/

相关文章:

javascript - 使用 JS 或 JQuery 将所有大写字母转换为标题大小写的最有效方法?

javascript - Typescript Cannot write file 会覆盖输入文件。编译 Ionic 3 应用程序时出错

javascript - 为什么最后一个元素总是在悬停时触发?

javascript - 我可以在不使用 javascript 的情况下开始这个简单的 CSS 转换吗

javascript - 横幅 javascript 变得更快

javascript - 在 Jquerymobile 中获取 slider 的值?

javascript - 如何使用 JavaScript 按标题选择元素并更新它

javascript - jQuery:使用children()比使用子选择器更有效

javascript - 使用 mocha 对 Node 模块进行单元测试,模块变量行为异常

javascript - 使用 React 路由器 React 中间件身份验证组件