简体   繁体   中英

Select specific anchor link with jquery

I have a menu structure like this:

<ul class="menu">
    <li class="parent">
        <a class="menu-link" href="http://url.com/#Id">Id</a>
    </li>
    <li class="parent">
        <a class="menu-link" href="http://url.com/#Id">Id</a>
    </li>
</ul>

and an English version where the menu is like this:

<ul class="menu">
    <li class="parent">
        <a class="menu-link" href="http://url.com/en/#Id">Id</a>
    </li>
    <li class="parent">
        <a class="menu-link" href="http://url.com/en/#Id">Id</a>
    </li>
</ul>

Using scrollspy, I'm detecting which section of the page is currently visible. So I can get the Id part of the anchor link. Now how do I select that specific anchor link?

I tried this:

$('.menu').find(":contains('#" + this.id"')" ).addClass('active');

But that doesn't work (otherwise I wouldn't be here!).

:contains will check html() / text() part of the anchor tag, you need to use attribute selector for href of anchor tag as shown below

$('.menu').find("a[href*='#" + this.id + "']" ).addClass('active');

JSFiddle Demo

More Information on attribute contains selector

what about to separate url (which should be SEO) and set id independent of url query by using data-binding? I hope you are using some template engine to render this html code. If not its ok only one attribute more.

for example:

<ul class="menu">
<li class="parent">
    <a class="menu-link" href="http://url.com/en/topic-for-women" data-id="1">Id</a>
</li>
<li class="parent">
    <a class="menu-link" href="http://url.com/en/topic-for-men" data-id="2">Id</a>
</li>

For this you can use very simple calling of jquery:

$(".menu .menu-link[data-id='2']").addClass("active");

here s link enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM