.on('click') with wildcard not not delegating as expected

时间:2019-03-19 14:57:15

标签: php jquery ajax

Will try to keep this simple so its not too much reading

I have a simple page with the following ...

$divid = 'append_here_$x;
$clickme = 'click_$x';

<div id='$clickme'>Click Me</div>

<div id='$divid'></div>

Then , I have a separate php file that builds content in a while loop generating a unique id for each div.

while ...
   $imgid = 'imgid_$z'  ...
   <div id='$imgid'>This was appended</div>

Finally, I have this just for testing and keeping things short

$( "[id^='imgid_']").on( "click", function() {
  alert('you clicked me');
});

This above works fine for the most part. If you were to click on click me, it will do ajax call and a post against the file with the while loop in it, return data and append it inside the append_here_ div. The problem is the new appended data that also has an id so yo can click will not respond to the simple click.

1 个答案:

答案 0 :(得分:1)

The way you link the click event to the elements of the page will not work for elements added later. You are linking the event to the elements present by the time you define the click events, but if you add items later, they won't have the event on them. You could do:

$(document).on('click', '[id^="imgid_"]', function() {
  alert('you clicked me');
});

That way, the event will be on the document, which is present at the startup, and everytime you click, it will check the selector (second parameter), so the new elements will respond to the click.