问题
I've come to maintain a piece of javascript that downloads some JSON data from the server, builds a new table row (like $('<tr></tr')
) and inserts it into the document.
The a
node is, at one point created like this:
var a = $('<a class="foo" href="#"></a>');
and later, an event is bound to it like this:
a.click(function () {
// yadda yadda
return false;
});
The only problem is that this doesn't seem to work. Neither does binding through on()
or the deprecated live()
. The handler is simply "ignored", never fires and the page scrolls to the top (due to the href="#"
). When binding the event, the element is already append
ed to DOM. Any help would be greatly appreciated.
Some contextual information that comes to mind: the element is created inside a loop iterating over the data, but that shouldn't be a problem unless javascript has some really weird stuff going on with scoping, plus everything else I try with the element works: I can change its content, styling, only the event binding doesn't work. And of course, the jQuery version, which is 1.8.3.
回答1:
EDITED
The .on() should be set up like this to work with dynamically created elements. Also, make sure to use Jquery version 1.8 (newest release)
Also, you need to prevent the standard action of the click if you don't want to scroll to the top.
Here is a working FIDDLE
var a = $('<a class="foo" href="#">ASD</a>');
a.appendTo($("body"));
$('body').on('click', 'a', function(e) {
e.preventDefault();
$(this).after('<br/><a class="foo" href="#">ASD</a>');
});
回答2:
You have various options. You can bind to the element or to the document.
BIND TO DOCUMENT:
$(document).on("click", "a.foo", function(event){
//do stuff here
});
When you bind to a document, you can freely create and destroy a.foo elements and they will all respond to your function.
BIND TO ELEMENT:
$("a.foo").on("click", function(event){
//do stuff here
});
When you bind to an element, the function is bound to all previously existing elements ONLY. So make sure you do this at the end of document load or at the end of your function.
I would recommend always binding to document!
回答3:
Two things come to my mind:
- The link has no text so you are not clicking it.
- You aren't even appending it to the dom.
Here there is a fiddle that works with code very similar to yours.
var a = $('<a class="foo" href="#">ASD</a>');
a.click(function() {
alert('a');
});
a.appendTo($("body"));
回答4:
You can use event delegation like so.
$('body').on('click','.foo',function(){
alert('foo');
});
This will allow you to set the event handler before the element is present.
回答5:
Try this:
var a = $('<a class="foo" href="#">ASD</a>');
$("body").html(a);
a.click(function() {
alert('a');
return false;
});
回答6:
Try binding the function within the scope of the function where you dynamically create the element.
$('a.foo').on('click',function(event){
//your code goes here
});
来源:https://stackoverflow.com/questions/13650261/jquery-cannot-bind-events-to-dynamic-elements