查找并禁用<a href="">

时间:2018-11-29 16:02:12

标签: javascript jquery html5 href

I have weird structure and want to disabled first element inside li.expanded using a[href="/abc"]. I have parent and child have same href and title is different. How can I select parent only element?

Here the code:

<ul class="n-right m-menu__link-list" id="main-right-menu">
    <li class="first leaf"><a href="/xyz" title="xyz-parent">xyz-parent</a></li>
    <li class="leaf"><a href="/pqr" title="pqr">pqr</a></li>
    <li class="last expanded"><a href="/abc" title="abc">abc</a>  //want to find this element and apply treatment

      <ul class="n-right m-menu__link-list" id="main-right-menu">
        <li class="first leaf"><a href="/abc" title="abc1">abc</a></li>  //not this one
        <li class="last leaf"><a href="/mno" title="mno">mno</a></li>
    </ul>
    </li>
</ul>

What I have tried, the function is working. it's selecting both a[href="/abc"] parent and child. I want to find and select only parent one.

openabcInNav: function() {
    var navEl = $('#main-menu, #main-right-menu li.expanded').find('a[href="/abc"]:nth-child(1)');
    navEl.addClass('doNotClose');
    navEl.on('click mouseover', function(event) {         
        event.preventDefault();
        $('nav.global-nav').find('li.expanded').toggleClass('show');
    });
},  

2 个答案:

答案 0 :(得分:1)

您可以使用:first选择器,该选择器将在第一次出现时返回其父项:

$('ul>li.expanded>a[href="/abc"]:first')

$('ul>li.expanded>a[href="/abc"]:first').css('background-color', 'green');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="n-right m-menu__link-list" id="main-right-menu">
  <li class="first leaf"><a href="/xyz" title="xyz-parent">xyz-parent</a></li>
  <li class="leaf"><a href="/pqr" title="pqr">pqr</a></li>
  <li class="last expanded"><a href="/abc" title="abc">abc</a> //want to find this element and apply treatment

    <ul class="n-right m-menu__link-list" id="main-right-menu">
      <li class="first leaf"><a href="/abc" title="abc1">abc</a></li> //not this one
      <li class="last leaf"><a href="/mno" title="mno">mno</a></li>
    </ul>
  </li>
</ul>

答案 1 :(得分:0)

a[href="/abc"]:nth-child(1)查看a[href="/abc"]中的第一个子对象

尝试使用:

a[href="/abc"]:nth-of-type(1)

这将返回与a[href="/abc"]匹配的第一个