zoukankan      html  css  js  c++  java
  • JS异步加载,JQ事件不被执行解决方法

    一,在我们实现动态生成HTML代码时会出现,使用JQ方法会不被执行,解决方法,如下:使用jquery的委托事件,将该方法委托到页面已经存在的一个节点上

    <!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="jquery-1.11.1.js"></script>
        <script>
            $(function () {
                $("#demo").delegate('.t1', 'click', function () {
                    alert("t1");
                });
                $("#demo").delegate('#t2', 'click', function () {
                    alert("t2");
                });
                $("#demo").delegate('.t3', 'click', function () {
                    alert("t3");
                });
                $("#demo").delegate('#t4', 'click', function () {
                    alert("t4");
                });
                Test();
            });
            function Test() {
                var strHtml = "<div class='t1'>t1</div>";
                strHtml += "<div id='t2'>t2</div>";
                strHtml += "<div class='t3'>t3</div>";
                strHtml += "<div id='t4'>t4</div>";
                $("#demo").html(strHtml);
            }
        </script>
    </head>
    <body>
        <div id="demo">
        </div>
        <div id="demo1">
        </div>
    </body>
    </html>

     二,经过以上测试,得出

    1》使用class和id触发的写法是一样的

    2》JS动态添加的HTML并不需要在绑定事件的节点内,一样可以触发成功

  • 相关阅读:
    步步为营-15-文件夹的操作
    步步为营-14-文件操作
    步步为营-13-日期转化
    步步为营-12-Dictionary-翻译
    步步为营-11-List<T>泛型的简单练习
    步步为营-10-string的简单操作
    步步为营-09-简单工厂类-计算器
    B. Fixed Points
    C. Cd and pwd commands
    Queries on a String
  • 原文地址:https://www.cnblogs.com/May-day/p/7212522.html
Copyright © 2011-2022 走看看