tags:

views:

141

answers:

2

I am adding tag at run time using jquery.

<a id=add class=add href=#>Test</a>

I want to fire the click event of this tag but it doesn't get fired.

I have already tried

$('#add').bind('click', function(e) {

e.preventDefault();
  alert('hello');

});

but nothing happens.

+2  A: 

You need to bind it using .live()

$('#add').live('click', function(e) {
  e.preventDefault();
  alert('hello');
});

The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation.

http://api.jquery.com/live/

Gerard Banasig
Awesome it works .But whats wrong with bind?
Dee
.live() method Attach a handler to the event for all elements which match the current selector, now or in the future.
Dee
Yup Dee is right, and to add to that .bind() only works for DOM w/c are added before the page has loaded. If you right click view source your page all the elements there can be selected by .bind() only. newly added DOM or on the fly created elements can be selected by .live()
Gerard Banasig
+1  A: 

Maybe you should use a valid XHTML:

<a id="add" class="add" href="#">Test</a>

And in the jQuery:

$('#add').live('click', function(e) {
    e.preventDefault();
    alert('hello');
});
TiuTalk
Who says he's using XHTML? What he's got is valid HTML.
cletus