zoukankan      html  css  js  c++  java
  • 解决使用jQuery采用append添加的元素事件无效的方法

    <html>
    <head>
    <script type="text/javascript" src="/jquery/jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
      $("button").live("click",function(){
        $("p").slideToggle();
      });
    });
    </script>
    </head>
    <body>
    <p>这是一个段落。</p>
    <button>请点击这里</button>
    </body>
    </html>

    但是随着jQuery的版本升级,自从jQuery 1.9及其以上已经无法使用live了,那么没有办法了吗,不是的,对于jQuery1.9版本及其以上可以使用on,其效果等同于live。下面的on的使用方法

    <script>
    $(document).on("click", ".waiting-save", function () {
      $(this).html('@T("Saving...")')
      $(this).attr("disabled", "");
    });
    </script>

    整个代码例子为:

    <!DOCTYPE html>
    <html>
    
    <head>
        <title></title>
        <meta charset="utf-8"/>
    </head>
    <body>
    <div>
       <form action=" " method=" " >
        <div class="list">
            <div class="addList">
                分部:
                <select>
                    <option>分部</option>
                    <option>分部1</option>
                    <option>分部2</option>
                </select>
                数量:<input type="text" value="123"/>
                <!-- <span class="add">添加</span>  -->
                 <input type="button" value="添加"  class="add"/>
            </div>
        </div>
        </form>
    </div>
    </body>
    
    <script type="text/javascript" src="./js/jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
        $(function(){
            //全局变量i
              i=0;
              $(".add").click(function() {
                  $(".list").append(function(){
                        return '<div class="delList'+i+'"> 分部: <select><option>分部</option><option>分部1</option><option>分部2</option></select> 数量:<input type="text" value="123"/><input type="button" class="del" value="删除"/> </div>';
                  });
                  i++;
              });
             $(document).on("click", ".del", function () {
                $(this).parent().remove();
             });
        })
    </script>
    </html>
    注意:
    1.button的问题
    <input type="button" value="添加" class="add"/>
    这句不能使用 <button class="add">添加</button>
    使用button标签的时候,添加的
    delList DIV会闪一下,闪了之后就会消失了,不能显示在页面上。
    2.input标签闭合问题。
    在编辑页面的时候,要记得标签要闭合,不闭合的话,会出现问题。

    参考网址:
    http://so.xiaohuihui.net/?a=url&k=6c98d343&u=aHR0cDovL3d3dy5idWJ1a28uY29tL2luZm9kZXRhaWwtNTcwMjgyLmh0bWw=&t=6Kej5Yaz5L2@55SoalF1ZXJ56YeH55SoYXBwZW5k5re75Yqg55qE5YWD57Sg5LqL5Lu25peg5pWI55qE5pa55rOVIA==&s=anF1ZXJ5IGFwcGVuZCDml6DmlYg=
    
    
  • 相关阅读:
    图解插入排序
    图解冒泡排序
    break 和continue的两种用法
    循环的使用选择
    jstl标签库使用报错index_jsp.java找不到问题
    [Android 除錯] Conflict with dependency
    jQueryMobile 網頁使用 ASP.NET Web API 服務
    Chart.js 與 ASP.NET MVC 整合應用
    HTML5 新增的 input 事件
    ASP.NET MVC 5 實作 GridView 分頁
  • 原文地址:https://www.cnblogs.com/xiaoxiao2014/p/5001075.html
Copyright © 2011-2022 走看看