简体   繁体   中英

How to prevent click event triggering for last li?

<ul>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>

I need to prevent click event for last li element. I tried like below,

$(document).on("click", "ul li:not(last-child)", function (e) {
//do something
}

But this is not working. Post your answers if came across the same.

Thanks in advance !!!

It should be :last-child instead of last-child in the selector string.

$(document).on("click", "ul li:not(:last-child)", function (e) {
   //do something
})

 $(document).on("click", "ul li:not(:last-child)", function (e) { console.log('clicked'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>test</li> <li>test</li> <li>test</li> </ul> 


Although event-delegation is only necessary if the elements are dynamically generated other ways bind handler directly.

$("ul li:not(:last-child)").on("click", function (e) {
   //do something
})

 $("ul li:not(:last-child)").on("click", function(e) { console.log('clicked'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>test</li> <li>test</li> <li>test</li> </ul> 


To avoid selecting nested li use direct child selector( > ) .

$("ul > li:not(:last-child)").on("click", function (e) {
   //do something
})

 $("ul > li:not(:last-child)").on("click", function (e) { console.log('clicked'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>test</li> <li>test</li> <li>test</li> </ul> 

You can also achieve this by li:not(:last)

 $(document).on("click", "ul li:not(:last)", function (e) { alert() }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>test</li> <li>test</li> <li>test</li> </ul> 

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