Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery use .on() with not selector

Tags:

I am using .on() function with this syntax:

$(".schemaTab").on("click", ".schema", function () {}) 

instead of .live() because I am adding .schema divs dynamically. Those divs have this code:

<div class="schema" id="SCH_16">    <img src="Img/btnRemove.png" class="ikona SCH_Remove" alt="Smazat" title="Smazat"> </div> 

But I need to exclude the img from click event of its parent div, so any idea how to do it?

I tried:

$(".schemaTab").not(".SCH_Remove").on("click", ".schema", function () {}) 

...but it didn't work and I don't know how to add the .not() inside the .on() code

like image 668
m3div0 Avatar asked Jul 04 '12 21:07

m3div0


People also ask

What is not () in jQuery?

The not() is an inbuilt function in jQuery which is just opposite to the filter() method. This function will return all the element which is not matched with the selected element with the particular “id” or “class”. Syntax: $(selector).not(A) The selector is the selected element which is not to be selected.

How do I select not this in jQuery?

jQuery :not() SelectorThe :not() selector selects all elements except the specified element. This is mostly used together with another selector to select everything except the specified element in a group (like in the example above).

What is the syntax is used to apply not equal filter on HTML elements using jQuery?

jQuery not() Method The not() method returns elements that do not match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are returned from the selection, and those that match will be removed.


2 Answers

.not() won't work because on method attaches event handlers to the currently selected set of elements in the jQuery object and uses the original selector to test whether the event should apply.

So I reckon selecting and then filtering in your case will do the trick.

API: http://api.jquery.com/on/

you could try this:

$(".schemaTab").on("click", ".schema", function (e) {      if (!$(e.target).is(".schemaTab")) {          // not stuff in here     }  }); 
like image 112
Tats_innit Avatar answered Sep 29 '22 14:09

Tats_innit


You can actually use the :not selector with the .on method, like so.

This is a cleaner solution than filtering results per Tats_innit's answer.

$('.schemaTab').on('click', '.schema:not(.booga)', function(event) {   // Fun happens here }); 

I'm using jQuery 1.11.0.

like image 27
Qasim Avatar answered Sep 29 '22 12:09

Qasim