开发者

confused with jquery after() behavior

Following is a piece of jquery code that is driving me nuts

var count = 0;
    $('#some-element-id').click(function(){
        var currentElement = '#new-div-id-'+count;
        $(currentElement).after($('<div id="new-div-id-'+(++count)+'">Hello World!<span class="delete_me">x</span></div>'));
});

$(".delete_me").click(function () {
  alert('Deleting!');
});

Now accordingly when I click on element with id some-element-id a new div is inserted and I see the x character. But clicking x doesn't do any thing. No error. As per http://api.jquery.com/after I can insert elements this way which is开发者_如何学编程 working fine. I can ee the new elements in DOM tree using Firebug. Now why no event is fired when I click on span? For some unknown reason I am forced to use jQuery 1.3.2 but that should not be a problem.

Update 1 I understand that I am trying to bind an even to an element that doesn't exist in the DOM. But please note that even is not fired, the event will be fired after the element is embedded in the DOM. I used following code and even it doesn't work

$("span.delete_me").live('click',function () {
  alert('Deleting!');
});

There is no error on the console. Update 2 Here is the actual rendered code http://jsfiddle.net/8sjcZ/


See http://jsfiddle.net/vKwm6/


Use the live method:

$(".delete_me").live("click", function () {
  alert('Deleting!');
});

At the time you call the .click method in your post, the "x" doesn't exist.


try

$(".delete_me").live('click',function () {
  alert('Deleting!');
});

your .click() is not working because the .delete_me class is not in DOM at time you call .click() so binding never takes place. .live() ensures that binding takes place for elements which are created at runtime.


hmmm you need to do it with live()

$(".delete_me").live('click',function () {
  alert('Deleting!');
});

live() will apply to dynamically added objects

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜