Giffary
Giffary

Reputation: 3128

How to add click event listener to each elements?

I use query to build a mobile app. First of all I use $.getJSON to retrieve data from json file:

$.getJSON('js/sura.json', function(data){
        $.each(data, function(key, value){
            //alert(key+' '+value['id']);
            buildList(value['id'], value['name'], value['number']);
        });
    });

There are more than 100 rows from json file.

After that, I need to put every lists to an elements name <ul id="list></ul>. Should I make new Javascript function then write the code:

function buildList(id, name, number){

    var name_elm = '<h3>'+name+'</h3>';
    var noq_elm = '<span>'+number+'</span>';

    var $list_elm = '<li>'+name_elm+''+noq_elm+'</li>';

    $('#list').append($list_elm);
}

After I use .append(...). I would like to add click listener to every lists (each list has unique id).

How should I write query to add listener to each <li></li>?

Upvotes: 0

Views: 348

Answers (2)

adeneo
adeneo

Reputation: 318182

This can be done more efficiently like this

$.getJSON('js/sura.json', function (data) {
    var container = $();

    $.each(data, function (key, value) {
        var h3   = $('<h3 />', {text : value.name}),
            span = $('<span />', {text : value.number}),
            li   = $('<li />', {
                id: value.id,
                on: {
                    click: click_function
                }
            });

        container = container.add(li.append(h3, span));
    });

    $('#list').append(container);
});

function click_function() {
    // do stuff on click
}

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can use event delegation:

var $list_elm = '<li class="noqele">'+name_elm+''+noq_elm+'</li>';
$('#list').append($list_elm);
}

And Code for click event:

$(document).on('click','.noqele',function(){
    //click event code...
});

Upvotes: 2

Related Questions