user1853803
user1853803

Reputation: 659

Three time firing of click event on dynamically created element

I am facing very simple problem. I am trying to add click event on the dynamically generated elements like this

$(document).ready(function(){
    $('ul').on('click', 'li.clickable', function() {
        console.log( $(this).text() );
    });
});
<ul id="codingView">
    <li id="" style="display:none;" class="clickable"><span></span></li>
</ul>

Here I have created two li elements dynamically.

The problem is that console is writing 3 times on every click on li. Why? Any workaround.

Edit

 var $box=$('#codingView li:eq(0)');
$('#codingView').empty();
$.each(data,function(key,value){
    console.log(this.topic);
    $box.find("span").html(this.topic);
    $box.css("display","block");
    $box.clone().appendTo("#codingView");       
});

Upvotes: 0

Views: 214

Answers (2)

OneOfOne
OneOfOne

Reputation: 99351

I'm not sure why your code isn't working, however this seems to work fine fiddle

<ul id="codingView"></ul>

$(function() {
    var cv = $('#codingView');
    cv.on('click', 'li.clickable', function() {
        console.log($(this).text());   
    });
    for(var i = 0; i < 5; ++i) cv.append($('<li/>', {'class' : 'clickable'}).html('<b>I AM #' + i + '</b>'));
});

//Edit : Updated the fiddle with your new code, altered it a little :

$(function() {
    var cv = $('#codingView');
    $('#codingView').empty();
    var data = [{topic: 1}, {topic: 2}, {topic: 3}];
    $.each(data,function(){
        console.log(this.topic);
        var li = $('<li/>', { 'class': 'clickable'}).append($('<span/>').html(this.topic));
        li.appendTo(cv);
    });

    cv.on('click', 'li.clickable', function() {
        console.log($(this).text());   
    });
});

Upvotes: 0

Bill Criswell
Bill Criswell

Reputation: 32921

It sounds like you might be nesting the <li>s inside of each other. I'd make sure the produced HTML is what you think it is.

Upvotes: 1

Related Questions