Roldan Roldan - 1 month ago 5
jQuery Question

How create a href through jquery .html and next use its event?

Well, My problem is described below:

I have this javascript code in order to created a href in a table:

$('#table').html('<a name="example" class="one">One</a><a name="example" class="two">Two</a>');


And then I wanna know which
a
tag I pressed.... something like this:

$("a[name=example]").click(function(e) {
var example= $(this).attr("class");
alert(example);
}


But this doesn't work...

Could you help me?

Thx 4 advance!

Answer

You should use event delegation on() to attach the click event to the fresh DOM (a tags) added dynamically to the page by your script :

$("#table").on('click','a[name=example]',function(e) {
  var example= $(this).attr("class");
  alert(example); 
})

Hope this helps.

$('#table').html('<a name="example" class="one">One</a><br><a name="example" class="two">Two</a>');

$("#table").on('click','a[name=example]',function(e) {
  var example= $(this).attr("class");
  alert(example); 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table">