我如何 select 具有 jQuery 的父元素
How do I select a parent element with jQuery
我有一个菜单,我想在其中将列表项和 link 设置为我在活动时设置的 "active" class url.
这是我的 HTML:
<ul id="featured-projects">
<li><a href="featured-project.php?id=1" title="Click to view 138 50th Street">138 50TH STREET</a></li>
<li><a href="featured-project.php?id=2" title="Click to view 147 East 86th Street">147 EAST 86TH STREET</a></li>
<li><a href="featured-project.php?id=3" title="Click to view 520 Fifth Avenue">520 FIFTH AVENUE</a></li>
</ul>
和jQuery:
$("#featured-projects li a").each(function() {
if(this.href == window.location.href) {
$(this).addClass("active");
$("li").addClass("active");
}
});
如何在不将 每个 列表项都设置为活动的情况下将列表项也设置为活动?
您要找的是parent()
。顾名思义,它总是选择匹配元素的父节点。完整描述在这里:https://api.jquery.com/parent/
$("#featured-projects li a").each(function() {
if(this.href == window.location.href) {
$(this).addClass("active");
$(this).parent().addClass("active"); //Select the parent element of the link in question and add the class
}
});
我有一个菜单,我想在其中将列表项和 link 设置为我在活动时设置的 "active" class url.
这是我的 HTML:
<ul id="featured-projects">
<li><a href="featured-project.php?id=1" title="Click to view 138 50th Street">138 50TH STREET</a></li>
<li><a href="featured-project.php?id=2" title="Click to view 147 East 86th Street">147 EAST 86TH STREET</a></li>
<li><a href="featured-project.php?id=3" title="Click to view 520 Fifth Avenue">520 FIFTH AVENUE</a></li>
</ul>
和jQuery:
$("#featured-projects li a").each(function() {
if(this.href == window.location.href) {
$(this).addClass("active");
$("li").addClass("active");
}
});
如何在不将 每个 列表项都设置为活动的情况下将列表项也设置为活动?
您要找的是parent()
。顾名思义,它总是选择匹配元素的父节点。完整描述在这里:https://api.jquery.com/parent/
$("#featured-projects li a").each(function() {
if(this.href == window.location.href) {
$(this).addClass("active");
$(this).parent().addClass("active"); //Select the parent element of the link in question and add the class
}
});