如何访问jQuery中动态创建的列表? [英] how to access dynamically created list in jquery?

查看:47
本文介绍了如何访问jQuery中动态创建的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无序的链接列表,这些链接是由Ajax动态创建的,我想为每个链接添加单击功能,但无法正常工作,请帮忙!

i have a unordered list of links, which are dynamically created by Ajax, and for each link i want to add click function to it, but it won't work, please help!

这是我的代码:

HTML :

<div id="sidebar">
  <li>
      <h2> list </h2>
      <ul id="list"></ul>
  </li>
</div>

JS :

//to create links
var str = '';
$.each(json.opts, function(i, opt) {
  var id = opt + '-list';
  str += '<li><a href="#" id='+ id +'>' + opt + '</a></li>';   //link
}
$("#list").html(str);

...
//to add click function to each links, this won't work
$("#list li").each(function (i) {
   alert(i + " : " + $(this).text());
});

推荐答案

应为 .click() 代替 .each() :

$("#list li").click(function (i) {
   alert(i + " : " + $(this).text());
});

如果调用此函数,则必须已经插入元素.否则,您必须使用 .live() :

And if you call this function, the elements must already be inserted. Otherwise you have to use .live():

$("#list li").live('click', function (i) {
   alert(i + " : " + $(this).text());
});

这篇关于如何访问jQuery中动态创建的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆