Only one of the two delegate functions works

I am trying to delegate the click action, but it only works like this:

$('input#doIt').on('click', { name: "Karl" } , function(event){ alert(event.data.name); }); 

but not this way:

 $('input').on('click', '#doIt' , { name: "Karl" } , function(event){ alert(event.data.name); }); 

According to the documentation, they should be the same. The first is associated with only one element, and the second is attached to two, but the selector reduces it to unity. Can anyone shed some light on this?

Here is the html

 <div class="row"> <div class="formLabel">Add Node:</div> <div class="formInput"> <input type="text" name="addNote"></div> </div> <div id="goTo" class="row"><input id="doIt" type="submit" value="Submit"></div> 
+4
source share
2 answers

According to the documentation, they should be the same.

No, the documentation says that selectors filter the descendants, not the actual element you connected the event to:

Selector

Type: String

A selector string to filter the descendants of the selected elements that trigger the event.

(My emphasis) In your case, input with id doIt not a descendant, you connect the event directly to it.

You used a delegated form by associating this event with the ancestor of doIt input , possibly on what contains your div.row elements:

 $("selector for the container of the rows").on('click', '#doIt', {name: "Karl"}, function(event) { alert(event.data.name); }); 

(I assume that you have a good reason to use delegation for this, and not just to bind directly to the doIt element - for example, perhaps this element will be deleted and re-created.)

+2
source

the first one works because you use direct on event and do not delegate it to any of your parent elements

 $('input#doIt').on('click', { name: "Karl" } , function(event){ 

here you simply fire the click event for input with the id doIt , which will not work if the input is added dynamically ..

and in the second - delegation, but then to the same element.

 $('input').on('click', '#doIt' , { name: "Karl" } , function(event){ alert(event.data.name); }); 

here, this will trigger a click event for all elements with doIt id inside the input, which is incorrect

you need to delegate it to the closest static parent container .. so this will work.

  $('div#goTo').on('click', 'input#doIt' , { name: "Karl" } , function(event){ ... 

note: you have two elements with the same Id doIt , which is invalid HTML .. change it to a class .. I changed the class entry here in the code above. strike>

+2
source

All Articles