【发布时间】: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