开发者

How to make function work after append

For example i'm using append, and for example i'm appendig button in to a div, and i have function $('button_id').click(... etc to work affter i append the div, how can i do that.I mean i get no errors, but the function is not starting, it's because i append and then i want to 开发者_如何学Cuse the function but how to do that, i tryed with delegate, but same thing.I tryed with function in the button tag , onmouseover and then the function thing, but nothing it gives me function not found.What is the solution ?

I have two events, one event is click event that appends button, the other event is click event that does something if the button that was appended is clicked, but that second event is not working ?


Try using :

$(elem).live(...)

It will bind event for now and in the future.


Firstly, it always helps if you show us the exact source code. $('button_id') is the incorrect selector to start with, try something more along the lines of $('#button_id') as your selector. Also, are you appending dynamic content? Anyways, I've always used the delegate() function quite successfully, but have you tried using the live() function? Also, one more thing to make sure of is that you have the newest version of jQuery as your source.

As was stated as well, you can not have duplicate ids, if you want to have a pointer, use class, instead of id="some_id" use class="appended". To select those using jQuery, use the selector like this $('.appended').


Try something like this it will work as per your expectations.

$("#button_id").click(function(){

  //On click code goes here

}).appendTo($("#div_id"));


It's difficult to determine the problem you're having without seeing your code, but delegate (or live) should be perfect for what you're trying to do:

$("body").delegate("#b", "click", function() { 
    alert("ok"); 
});

$("#example").append('<input type="button" id="b" value="Click" />');

The click handler above will fire when an element with id="b" is clicked, whether or not that element happens to be in the DOM right now or not.

However, as others have noted, it's important to remember that IDs need to be unique within a document, so by the sounds of it you may be better of using classes instead.

You can see an example of the above code running here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜