jQuery: Highlight link that have the same href as another
I'm working on a project, where I want to highlight the link (in a menu) that has the same href as another link on the site (in .container).
<ul class="menu">
<li><a href="about.html">Link 1</a></li>
<li><a href="portfolio.html">Link 2</a></li>
<li><a href="contact.html">Link 3</a></li>
</ul>
<div class="container">
<a href="contact.html">Go to Contact</a>
</div>
JS:
$("a").filter(function() {
return this.href === $('.container a').href;
}).addClass("equalHref");
Do you know how I can achiev开发者_如何学JAVAe this?
$('a:[href="' + $('.container a').attr("href") + '"]').addClass("equalHref");
Test here
Your solution is very nearly correct:
$("a").filter(function() {
// use jQuery.attr to access href
return this.href === $('.container a').attr("href");
}).addClass("equalHref");
or:
$("a").filter(function() {
// expose DOM object and access href property
return this.href === $('.container a')[0].href;
}).addClass("equalHref");
var strHref = $('.container a').attr("href");
$("a[href=" + strHref + "]")addClass("equalHref")
http://jsfiddle.net/8BRyG/
fiddle here.
精彩评论