0

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>?

2 Answers 2

2

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...
});
Sign up to request clarification or add additional context in comments.

2 Comments

too fast for us mortals ;)
@Moob:Indeed...Thats what stackoverflow does.
1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.