user824624
user824624

Reputation: 8056

can't bind to click event in jquery

It is a silly problem to make a li dom, add the li to ul, and enable the click on the li dom. The code snippet works by adding the li dom to the ul,

var li = '<li><a href="#" data-action="app">' + name +'</a></li>';
$("ul").append( li ); 
$(li).bind('click',onClick);
function onClick(e){
    console.log('click   ',$(this).html());
}

but when I use the $(li).bind('click',onClick); it doen'st seem to work, I am very confused why ?

Upvotes: 0

Views: 1412

Answers (3)

CodingIntrigue
CodingIntrigue

Reputation: 78525

li is not a jQuery element here. Wrap the HTML within a $() call to turn it into one:

var li = $('<li><a href="#" data-action="app">' + name +'</a></li>');
$("ul").append( li ); 
$(li).bind('click',onClick);
function onClick(e){
    console.log('click   ',$(this).html());
}

At the moment, you are appending raw HTML to the <ul>, then creating a new element again when you attempt to bind. This newly created element is never added to the DOM and therefore the event is never fired.

You can circumvent the need to .bind every time an element is added by using event delegation:

$(function() {
    // Only need to bind this once
    $("ul").on('click',"li", function() {
        console.log('click   ',$(this).html());
    });
});

// Call this any time you want to add a new li to the list
function addLi() {
    var li = '<li><a href="#" data-action="app">' + name +'</a></li>';
    $("ul").append( li ); 
}

Upvotes: 2

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

It does not work because li is just a string containing the HTML you inserted, not a reference to the DOM element itself. You might want to do this:

var $li = $('<li><a href="#" data-action="app">' + name +'</a></li>').appendTo('ul'); 
$li.bind('click',onClick);
function onClick(e){
    console.log('click   ',$(this).html());
}

Upvotes: 0

bipen
bipen

Reputation: 36531

use on event delegation

 $('ul').on('click','li',onClick);

function onClick(e){
  console.log('click   ',$(this).html());
}

or

$('ul').on('click','li',function(){
  console.log('click   ',$(this).html());
}

Upvotes: 0

Related Questions