开发者

Jquery dynamically create link

I 开发者_StackOverflow中文版have a piece of JQuery that creates a row in a table and in one of the cells there is an X that is surrounded by a class. When it is dynamically created and then clicked on the click listener does not fire. Here is the code.

$('#add').click(function() {
   $( '#table' ).append('<td class="x">X</td></tr>');
});
$('.x').click(function() {
  alert('Fired');
});


Since the <td> element does not yet exist when you register your event handler, you have to use live() or delegate() for the handler to be triggered later:

$(".x").live("click", function() {
    alert("Fired");
});


$(".x").live("click", function()
{
   alert("Fired");
});

Live adds events to anything added later in the DOM as well as what's currently there.


Instead of

$('.x').click(function() {
  alert('Fired');
});

Change to this

$('.x').live('click', function() {
  alert('Fired');
});

It binds the click function to any created element with class x


You need to use the .live function for content that's dynamically generated.

so replace

$('.x').click(function() {

with

$('.x').live('click',function() {


You are first creating the listener to all .x elements (of which there are presumably zero), then later adding new .x elements.

There are two solutions: one is to use jQuery live, the other is to rewrite your code:

var xClickHandler = function() {
    alert('Fired');
};
$('#add').click(function() {
    $('#table').append(
        $('<td class="x">X</td></tr>').click(xClickHandler);
    );
});


Use live instead of click:

$('.x').live("click", function() {
    alert('Fired');
});


The html you are appending to the table has a typo, you have missed out the beggining tr tag:

$('#add').click(function() {
   $( '#table' ).append('<tr><td class="x">X</td></tr>');
});
$('.x').click(function() {
  alert('Fired');
});


I think you need to use the live method. http://api.jquery.com/live/

$('.x').live('click', function() {
  // Live handler called.
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜