开发者

jquery problem with toggle event only fireing on the 2nd click

开发者 https://www.devze.com 2022-12-24 08:12 出处:网络
Can anyone explain why the following jquery only fires the 2nd toggle event and how to fix it?Specifically, every time I click the nested < a > element it brings up the alert \"2nd click\".

Can anyone explain why the following jquery only fires the 2nd toggle event and how to fix it? Specifically, every time I click the nested < a > element it brings up the alert "2nd click".

I tested the selector to make sure it was selecting the element properly and it does, or at least it inserted a class without any problems.

The selector is selecting the very last node in the unordered list that has an anchor tag.

$("#nav li:not(:has(li)) a").toggle(function() { //1st click
              alert("1st Click");
        }, function() { //2nd click
            alert("2nd Click");
        });

Nested HTML structure that fails:

<ul id="nav">
    <li>
      <span>stuff</span>
      <a href="#">Cat 1</a>
        <ul>
           <li>
               <span>stuff</span>
               <a href="#">Subcat1</a>
                 <ul>
                    <li>
                       <span>Stuff</span>
                       <a href="#">Subcat Details</a>
                    </li>
                 </ul>
           </li>
        </ul>
    </li>
</ul>

However, this works right and fires both click events:开发者_StackOverflow

<ul id="nav">
    <li>
      <span>stuff</span>
      <a href="#">Cat 1</a>
    </li>
</ul>


Converting to answer to close this out

The handler/code you have works ok in testing here, it looks like you have other event handlers that are either erroring or blocking the click from occuring on those anchors.

Make sure to check that the other event handlers on those nested <a> elements are behaving correctly, seems the error is there.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号