使用jquery在动态生成的列表项上单击事件 [英] Click event on dynamically generated list items using jquery

查看:88
本文介绍了使用jquery在动态生成的列表项上单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态生成的列表,然后我点击该项目并将 index()传递给另一个函数。

I have a list being dynamically generated and then I click on the item and pass the index() to another function.

问题是这个列表是动态填充的,当我执行点击事件时,我的代码没有响应。但是,如果我在列表中添加了几个静态li元素,除了动态填充的元素之外,那些静态元素也可以工作。非常奇怪。

The problem is that this list is being populated dynamically and my code does not respond when I do click event. BUT, if I add a couple of Static li elements to the list in addition to the dynamically populated ones those Static ones work. Its very odd.

一些代码:

这会动态创建列表:

function SetOpenRecentURL( openRecentURL ) {

 $('#recentProjectsId').append('<li>' + openRecentURL + '</li>')
 }

这是要通过的点击事件Index():

This is the click event to pass the Index():

$('#recentProjectsId li').on('click', function () {
        var projIndex = $(this).index();
        console.log(projIndex)
        OpenProject()

    })

带有一些静态李的HTML

The HTML with a few Static Li's

<div class="recentProjects" id="recentProjectsId">
<li>Test 1</li>
<li>Test 2</li>
        </div>

当我运行我的程序时,我的列表看起来很完美,包括我的静态li和我的动态,但是我无法点击动态的,只有静态。

When I run my program my list looks perfect and includes my static li plus my dynamic ones, but I cannot click on the dynamic ones, only static.

推荐答案


当我运行程序时,我的列表看起来完美,包括我的静态li和我的动态,但我不能点击动态的,只有静态。

When I run my program my list looks perfect and includes my static li plus my dynamic ones, but I cannot click on the dynamic ones, only static.

那是因为,如果您的代码绑定单击处理程序,它只绑定到绑定侦听器时页面中的元素。设置点击监听器只是略有不同,它将通过利用事件委派来实现:

That's because, the way your code binds the click handler, it is only bound to elements in the page at the time that the the listener is bound. Set up the click listener just a little differently and it will work, by taking advantage of event delegation:

$('#recentProjectsId').on('click', 'li', function () {
    // snip...
});

通过为<指定一个额外的选择器参数code> .on():

By specifying an additional selector argument to .on():


用于过滤所选元素后代的选择器字符串触发事件。如果选择器为null或省略,则事件始终在到达所选元素时触发。

A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.






请注意,您的HTML目前无效。 < li> 元素仅在< ul> s,< ol> s内有效,且< menu> s。


Note that your HTML is currently invalid. <li> elements are only valid inside of <ul>s, <ol>s, and <menu>s.

这篇关于使用jquery在动态生成的列表项上单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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