Deepak K
Deepak K

Reputation: 339

How to attach event on HTML elements which I have created using jquery on the fly?

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

Answers (5)

Joseph
Joseph

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

Christofer Eliasson
Christofer Eliasson

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

mattn
mattn

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

Munchies
Munchies

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

Zweer
Zweer

Reputation: 124

Try this:

var li = $('<li>').attr({
    id: "print"
}).click(function() {
    alert(this);
    consol.log(this);
});

Upvotes: 1

Related Questions