开发者

Possible to manipulate javascript generated elements?

I have a page dynamically generated with javascript and it contains several input fields and a button. When I click the button, nothing happens...Is it because it is a javascript object and not a "real" dom object? If so, is th开发者_StackOverflow中文版ere a way to interact with the object?

I just wrote a simple alert to see if the button is even working.

jQuery("#button").click(function() {
   alert("yes it's working");
});

On first page load this works...I believe on first page load it is PHP generated and when I click to another section, this same button will show up BUT the page does not refresh so this leads me to believe when I click on to another section, it is dynamically re-generated with JS.

Now if I click the button, nothing happens...no errors or no alerts...


You need to use .live because at the point in time when you assign the handler the element doesn't exist.

$('#button').live('click', function() {
});

You should also look into delegate if you're doing this with multiple elements for efficiency purposes.


I think I get what you're saying.

When you run jQuery('#button'), it searches for the elements then and there. The event is attached to the button itself, not to the query string #button.

jQuery does, however, offer the behavior you want.

jQuery('#button').live('click', function () { /* on click event */ });

live attaches to the query string, not the elements, so it will apply to any #button ever generated in the future.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜