【问题标题】:Looping through elements with jQuery使用 jQuery 循环遍历元素
【发布时间】:2018-06-05 05:05:51
【问题描述】:

我正在尝试循环浏览一些导航 HTML,因为我需要动态修改一些项目。具体来说,我将如何使用类 Droppable 遍历每个项目并获取某些孩子的 jQuery 对象。我在下面发布了我的代码,上面有一堆星号(*),表示我需要作为 jquery 对象操作的东西的注释。

<nav id="sitenav">
    <ul class="container ul-reset">
        <li class="droppable "> ****** foreach of these
            <a class="RootNode" id="Help" href="javascript:;">HELP</a> ****** I need this
            <div class="mega-menu">
                <div class="container cf">
                    <div style="display: inline-block;">
                        <ul class="ul-reset"> ****** and I need this 
                            <a class="heading disabled" id="Help_Help" href="javascript:;">
                                <h3>Help</h3>
                            </a>
                            <a id="ContactUs" href="/ContactUs/">Contact Us</a>
                            <a id="UserGuides" href="/Help/">User Guides</a>
                        </ul>
                    </div>                                
                </div>
            </div>
        </li>

        {more lis with the same structure...}

    </ul>
</nav>

我尝试了下面的方法,但我得到一个错误,它没有 find 方法,我认为它会是因为我认为这将是每个循环中当前 jQuery 包装的 DOM 元素。

$("li.droppable").each(function (index) {
    var header = this.find("a.RootNode");
    var col = this.find("ul.ul-reset");
});

【问题讨论】:

    标签: javascript jquery html each


    【解决方案1】:

    .find() 是一个 jQuery 方法,你不能在 DOM 对象this 上调用它。

    您可以改为在 jQuery 对象 $(this) 上调用 .find() 方法,所以它应该是:

    $("li.droppable").each(function(index) {
      var $this  = $(this);
    
      var header = $this.find("a.RootNode");
      var col    = $this.find("ul.ul-reset");
    });
    

    【讨论】:

    • 最好保持 DRY 和缓存 var $this = $(this);
    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 2010-10-28
    • 2018-04-13
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多