zoukankan      html  css  js  c++  java
  • jq为动态创建的元素绑定事件

    jquery中的on()为新添加的动态元素绑定事件

    html代码:

    <div>
      <p>弹出</p>
      <button>添加元素</button>
    </div>

    jq代码:

    $("button").click(function(){
      $("button").before("<p>"+"新建的"+"</p>")
    })
    $("div p").each(function(){                         //点击按钮生成的元素p,无法绑定事件:alert(”123“)
      $(this).on("click",function(){            
        alert("123")
      })
    })
    $("div p").each(function(){                         //点击按钮生成的元素,依然可以绑定事件:alert("123")
      $(this).parent().on("click","p",function(){              //.on前面是元素p的父级,第二个参数,是绑定事件对象。
        alert("123")
      })
    })

     希望对大家有帮助,live高版本移出了!建议大家不要用了!

  • 相关阅读:
    数据库设计范式
    SQL 触发器
    SQL查询上月和本月两个月的语句
    angularjs学习总结 详细教程
    指令
    重复 HTML 元素
    AngularJS 数据绑定
    AngularJS 指令.
    AngularJS 数组
    AngularJS 对象
  • 原文地址:https://www.cnblogs.com/ash-sky/p/9620815.html
Copyright © 2011-2022 走看看