简体   繁体   English

使用jQuery在填充列表中的每个项目上单击事件

[英]Click event on every item on populated list with jQuery

Here is how I populate my list: 这是我填充列表的方式:

function bingNetworksList(myList) {
    var list = '';
    for (i = 0; i < myList.length; i++) {
      list += '<li><a href="#">' + myList[i] + '</a></li>';
    }

    $('#myList').empty();
    $('#myList').append(list);
}

Here is my html file: 这是我的html文件:

<ul id="myList"></ul>

I want to add a click event for every item of list (without having separate ids): 我想为列表的每个项目添加click事件(没有单独的ID):

$(function() {
  $('#myList').click(function() {
    var listItem = this.find('a').text();
    console.log(listItem); // never logged
  });
});

However, when I click at a list item, click event doesn't fire. 但是,当我单击列表项时,不会触发click事件。

What am I doing wrong? 我究竟做错了什么?

I can only assume there's a js error in your console. 我只能假设您的控制台中存在js错误。

I've created a working sample for you. 我为您创建了一个工作样本。 We can use event delegation and then retrieve the DOM node that was clicked. 我们可以使用事件委托,然后检索被单击的DOM节点。 You need to ensure you call the bingNetworksList [assume typo in here and meant binD ;)] function when the DOM ready event has fired. 当DOM ready事件触发时,您需要确保调用bingNetworksList [在这里假设输入错误并表示binD;)]函数。

function bingNetworksList(myList) {
    var list = '';
    for (i = 0; i < myList.length; i++) {
      list += '<li><a href="#">' + myList[i] + '</a></li>';
    }

    $('#myList').empty();
    $('#myList').append(list);
}

$(function() {
  var list = ["foo", "bar"]
  bingNetworksList(list);
  $('#myList').click(function(evt) {
    var listItem = $(evt.target).text();
    console.log(listItem); // never logged
  });
});

You need to wrap this inside $ as like this: 你需要用this里面$的是这样的:

$(function() {
  $('#myList').click(function() {
    var listItem = $(this).find('a').text();
    console.log(listItem); // will always be logged
  });
});

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

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