简体   繁体   English

如何将点击事件监听器添加到每个元素?

[英]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从json文件中检索数据:

$.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. json文件中有100多行。

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: 之后,我需要将每个列表放入元素名称<ul id="list></ul> 。如果我要创建新的Javascript函数,请编写代码:

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(...) . 在我使用.append(...) I would like to add click listener to every lists (each list has unique id). 我想将点击侦听器添加到每个列表(每个列表都有唯一的ID)。

How should I write query to add listener to each <li></li> ? 我应该如何编写查询以向每个<li></li>添加侦听器?

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...
});

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM