Reputation: 339
var li = $("<li>").attr({
id: "print",
click: function(e){
alert(this);
console.log(this);
}
});
I have tried this code but it invokes sooner the code generates the HTML.
Upvotes: 0
Views: 72
Reputation: 119847
var li = $("<li>",{
id: "print" //the second parameter accepts properties as an object
}).on('click',function(e){ //.on() binds the event to that element
console.log(this);
});
or alternatively:
var li = $("<li>",{
id: "print" //the second parameter accepts properties as an object
click: function(e){ //attach the event as part of the properties
console.log(this);
}
});
Upvotes: 2
Reputation: 33865
Either you can make use of event-bubbling and attach a delegated event listener to a parent node. Doing so, you can attach the event-listener before you actually add the element to the DOM.
Or you could attach the element to the DOM before you try to attach the event listener:
$("<li>")
.attr({ id: "print"})
.appendTo("body") // Or wherever you want to put it
.on("click", function(e){
alert(this);
console.log(this);
});
Upvotes: 0
Reputation: 7723
use 'click' method.
var li = $("<li>").attr({
id: "print"
}).click(function(e) {
alert(this);
console.log(this);
});
Or if you want to attach event to dynamic generated elements, use $.live
function.
If you use jQuery mobile, i must say another answer.
Upvotes: 0
Reputation: 444
You can bind an event to a tag with .on()
An example:
$('li#print').on('click',function(e){
alert("Something" + $(this));
});
Upvotes: 0
Reputation: 124
Try this:
var li = $('<li>').attr({
id: "print"
}).click(function() {
alert(this);
consol.log(this);
});
Upvotes: 1