js 给动态li添加动态点击事件

试了网上的on,live,bind绑定,都不起作用。最后看到https://bbs.csdn.net/topics/390414057 

上的代码。试了一遍,demo ok。

附上demo:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var ul = $("ul");
            $(document).on("click", "li.new", function() {
                alert($(this).text());
            });
            $("#addLi").click(function() {
                ul.append("<li class=\"new\">"+(ul.children("li").size()+1+"li")+"</li>");
            });
        });
    </script>
</head>
<body>
    <ul id="ul">
        <li class="new">1</li>
        <li class="new">2li</li>
        <li class="new">3li</li>
    </ul>
    <input type="button" value="click" id="addLi" />
</body>
</html>

我的实践代码:

HTML代码:

<div class="infoShow" style="margin-top:5px;">
                                <ul id="info">
                                   
                                </ul>
                            </div>

js代码: 

 
$("#info").append("<li class=\"new\" >"+info_scroll+"</li>");
                            $(document).on("click","li.new",function(){
                                console.log("异常信息查询");
                                $.ajax({
                                    url:'/getEventDataById/',
                                    type:'post',
                                    data:{"appcontent":appcontent}
                                }).done(function(data){
                                    ShowDiv('MyDiv','fade');
                                    document.getElementById('info_projectname').innerText=data.project_info[0];
                                    document.getElementById('info_taskname').innerText=data.project_info[1];
                                    document.getElementById('info_cameraid').innerText=data.project_info[2];
                                    document.getElementById('info_tempValue').innerText=data.project_info[3];
                                    document.getElementById('info_tempRect').innerText=data.project_info[4];
                                    document.getElementById('info_image_temp01').src=data.imageTempFilename_0;
                                    document.getElementById('info_image_temp02').src=data.imageTempFilename_1;
                                    document.getElementById('info_image_exception').src=data.exception_imagepath;
                                })
                            })

猜你喜欢

转载自blog.csdn.net/weixin_38383877/article/details/87940866
今日推荐