【问题标题】:Iterate through loaded HTML file elements JQuery遍历加载的 HTML 文件元素 JQuery
【发布时间】:2018-04-11 14:06:42
【问题描述】:

我目前正在开发一个网站。使用 JQuery 中的 .load() 函数将标题加载到主“搜索”页面中。但是,当我尝试遍历页面中的 [href] 时,它找不到它们,因为加载的标题链接尚未添加到 DOM 中(大概)。

function getCurrentPage(){
        var count = 0;
        $(".navLinks").each(function() {
            count+=1
            console.log('this.href' + this.href)
            console.log('windowloc' + window.location.href)
            if (this.href == window.location.href) {
                $(this).addClass("active");
            }
        });
        console.log('# of hrefs' + count)
    }

这是我编写的一个函数,用于向当前页面添加一个 css 类,但是这个循环不起作用,因为它在 DOM 上找不到那些(.navLinks 类被添加到来自加载的 header.html 文件的所有链接)。感谢您的帮助!

<header>
<nav class="top-bar nav-desktop">
    <div class="wrap">
        <div class="top-bar-left">
            <div class="logo">
                <img class="logo-image" src="repairrepo_logo-02.png" width="250" height="184"></img>
                <p class="site-logo">DNA Damage and Repair Database</p>
            </div>
        </div>
        <div class="top-bar-right">
            <ul class="menu menu-desktop">
                <li><a href="index.html" class = 'navLinks'>HOME </a></li>
                <li>
                    <div class="dropdown">
                        <button class="dropbtn">BROWSE
                        <i class="fa fa-caret-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" class = 'navLinks'>HUMAN </a>
                            <a href="#" class = 'navLinks'>MOUSE</a>
                            <a href="#" class = 'navLinks'>ARABIDOPSIS</a>
                            <a href="#" class = 'navLinks'>PLANT</a>
                        </div>
                    </div>
                </li>
                <li><a href="search.html" class = 'navLinks'>SEARCH</a></li>
                <li><a href="download.html" class = 'navLinks'>DOWNLOAD</a></li>
                <li><a href="help.html" class = 'navLinks'>HELP</a></li>
            </ul>
        </div>
    </div>
</nav>

这是添加并附加到主搜索页面上 ID 为“header”的 div 的“header.html”文件。

【问题讨论】:

  • 您何时以及如何致电getCurrentPage()
  • 我只是在我的 jquery 脚本中的 document.ready 之后直接调用它

标签: javascript jquery html css


【解决方案1】:

你猜对了,

它找不到它们,因为加载的标题链接尚未添加到 DOM 中

.load() 是异步的,并且有一个在完成后执行的回调,您应该在此处调用您的函数:

$('#someDiv').load('someHtml.html', getCurrentPage);

请注意,您必须通过引用传递函数(没有()),否则它将在load() 完成之前执行。

【讨论】:

  • 所以我把它放在了js脚本的开头,但是'count'变量仍然打印出0...
  • 添加相关html以获得更准确的答案
  • 如果你把console.log('count : ', $('.navLinks').length) 放在getCurrentPage 函数中会得到什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 2010-09-15
相关资源
最近更新 更多