如何查看父ID中href的子值并检查它是否与当前URL匹配?然后,将一个类应用于父类,将一个类应用于匹配的子元素。
<!-- notice the ID on the li - "aboutsection" -->
<ul id="mainnav" class="nav navbar-nav">
<!-- About -->
<li class="dropdown jsb-fw" id="aboutsection"><a href="#"
data-hover="dropdown" data-delay="100" data-close-others="false"
class="dropdown-toggle">About</a>
<ul class="dropdown-menu">
<li class="grid-output">
<div class="row">
<div class="col-sm-3 about">
<h3 class="menuHeading">About US</h3>
<ul>
<li><a
href="http://localhost:8500/mysite/pagetestcurrent.cfm">Link to this page </a></li>
<li><a
href="http://localhost:8500/mysite/anotherpage.cfm"> Link to another page </a></li>
</ul>
</div>
</div>
</li>
</ul>
</li>
</ul>
<!-- if we are on any of the pages in the dropdown menu (which would
be either'pagetestcurrent' or 'anotherpage' as in the example above as
children of the about section), put a currentTab class on the above li
with the ID 'aboutsection'-->
jQuery将类添加到id“aboutsection”。无论子项中的href值如何,目前都会添加该类。
<script>
$('#aboutsection a').filter(function(){
return this.href = window.location.href;
}).parent().addClass('currentTab');
</script>
答案 0 :(得分:0)
试试这个:
$('#mysection a').filter(function (){ return this.href==window.location.href}).closest('#mysection').addClass(...)
OR
$('#mysection:has(a[href='+window.location.href+'])').addClass(...)
答案 1 :(得分:0)
我建议:
$('a').filter(function(){
return this.href == window.location.href;
}).parent().addClass('currentTab');
JS Fiddle demo(请注意,在JS Fiddle中,头文的URL与加载内容/结果的帧的URL不同。)
过滤器比较href
属性(浏览器返回的绝对URL,而不是.attr('href')
方法,它返回属性中的任何字符串,无论是相对的,绝对的还是简单的片段/ id
)并将其与页面的当前window.location
进行比较。
参考文献: