0

I have two php file file1.php and file2.php, file1.php send something with ajax to file2.php,

return data from file2.php, like

echo "<a class='test' id='test'>click me</a>";

In file1.php, I use innerHTML to display it

document.getElementById("test2").innerHTML=data;

I want click the a tag link and alert("something")

$("#test").clicl(function(){
    alert("hello");
});

The problem is I cant select the a tag link with Id attribute or Class attribute, how to do it? Thank you very much.

Jason Z
  • 265
  • 1
  • 6
  • 12

1 Answers1

2

jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

$(document).on('click', '#test', function(){
    alert("hello");
});
Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119