Roldan
Roldan

Reputation: 39

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!

Upvotes: 1

Views: 54

Answers (2)

Tinsten
Tinsten

Reputation: 356

This is how you should do it.

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

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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">

Upvotes: 1

Related Questions