为什么不$()。click()工作< li>由pageinit生成? [英] Why doesn't $().click() work on <li> generated by pageinit?

查看:77
本文介绍了为什么不$()。click()工作< li>由pageinit生成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击功能适用于< li> 元素,该元素属于HTML,但不适用于< li> 在pageinit上以编程方式加载的元素。我不明白为什么不。 (此代码只需运行)

The click function works for the <li> element that is part of the HTML but not for the <li> elements loaded programmatically on pageinit. I can't figure out why not. (this code has all it needs to run)

<!DOCTYPE html>
<html>
<head>
        <meta name="viewport" content="width=device-width, initial-scale=1"> 
        <link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.css" />
        <script src="http://code.jquery.com/jquery.js"></script>
        <script src="http://code.jquery.com/mobile/latest/jquery.mobile.js"></script>   
</head>
<body>
    <div id="thelists" data-role="page">

        <div data-role="header">
            <h1>My Title</h1>
        </div><!-- /header -->

        <div data-role="content">   
            <p>Hello world</p>
            <ul id="allyourlists" class="current" data-role="listview" data-filter="false">
                <li><a href="index.html" data-role="button" id="delalist">List0:</a></li>
            </ul>       
        </div><!-- /content -->

    </div><!-- /page -->
    <script>
    //Why is delete button not firing? 
    $('#thelists').bind('pageinit', function(event) {
        console.log('in bind pageinit for yourlists');
        var thelists = ["list1", "list2"];
        console.log(thelists);
        $.each(thelists, function(index, alist) {
            $('#allyourlists').append('<li><a href="index.html" data-role="button" id="delalist">List: ' + alist + '</a></li>');
        });
        $('#allyourlists').listview('refresh');
    });

    //gets the val of val1 from the previois call
    $("#delalist").click(function (e) { 
        e.stopImmediatePropagation();
        e.preventDefault();
        alert ('in delalist') ;
    });   

    </script>

</body>
</html>


推荐答案

使用已弃用的直播功能:

$("#delalist").live('click',function (e) { 
    e.stopImmediatePropagation();
    e.preventDefault();
    alert ('in delalist') ;
});  

或在上使用(jQuery> 1.7) :

or use on (jQuery > 1.7):

$('body').on('click', "#delalist", function (e) { 
    e.stopImmediatePropagation();
    e.preventDefault();
    alert ('in delalist') ;
});  

另外我建议使用和不是 id 因为 id s应唯一

Also I would suggest using a class and not an id because ids should be unique

这篇关于为什么不$()。click()工作&lt; li&gt;由pageinit生成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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