Why is my jQuery warning displayed twice?

I am using jQuery. I have a problem when notifying list ids twice, not once.

List:

<ul id="testnav">
    <li> <a href="#">Page 1</a></li>
    <li> <a href="#">Page2..</a>
        <ul id="subnav">
            <li id="content_1"><a href="#"> Page3</a></li>
        </ul>
    </li>
</ul>

Code:

$("li").click(function(){
    var current_id = $(this).attr('id');
    alert(current_id);
    // These alert two times, one is empty and another one is content_1
});

Why turns off code notification twice? How to execute it in one go?

+3
source share
7 answers

$ ("li"). click () applies the click event to all LIs on the page.

When you click

<li> <a href="#">Page2..</a>
     <ul id="subnav">
          <li id="content_1"><a href="#"> Page3</a></li>
     </ul>
</li>

In fact, you click on the external LI and internal LI, which may cause the event to fire twice. The external LI has no identifier, so it is empty, and the internal LI has the identifier "content_1", so it is displayed.

It makes sense?

+12
source

event.stopImmediatePropagation(); , :

$("li").click(function(event)
{
       event.stopImmediatePropagation();
});
+9

<li>, <li>.

<li>, <li> <li>

HTML , "Content_1" "OUTER-LIST-ITEM", , ...

<ul id="testnav">
    <li> <a href="#">Page 1</a></li>
    <li id="OUTER-LIST-ITEM">
        <a href="#">Page2..</a>
        <ul id="subnav">
            <li id="content_1"><a href="#"> Page3</a></li>
        </ul>
    </li>
</ul>
+8

.

+4

, , DOM.

:

    $("li").click(function(event){ 
      var current_id=$(this).attr('id'); 
      alert(current_id);  
      event.stopPropagation();
    });
+1

$( "li" ) . , , id = content_1, , .

0

It alerts you about this once for each, and your link - in two lists. To fix this, assuming you want subnav elements to run, change the first line of your code to

$("#subnav li").click(function(){

If you need more lists, create a class to identify the lists that you want to attach to the click event.

0
source

Source: https://habr.com/ru/post/1702697/


All Articles