javascript – 使用jquery在动态生成的列表项上单击事件

前端之家收集整理的这篇文章主要介绍了javascript – 使用jquery在动态生成的列表项上单击事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个动态生成的列表,然后我点击该项目并将index()传递给另一个函数.

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

一些代码

这会动态创建列表:

function SetOpenRecentURL( openRecentURL ) {

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

这是传递Index()的click事件:

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

    })

带有一些静态Li的HTML

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

这是因为,您的代码绑定点击处理程序的方式,它只绑定到绑定侦听器时页面中的元素.设置点击监听器just a little differently,它将通过利用事件委托来工作:

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

通过为.on()指定其他选择器参数:

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> elements are only valid inside of <ul>s,<ol>s,and <menu>s.

原文链接:https://www.f2er.com/jquery/156554.html

猜你在找的jQuery相关文章