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高版本移出了!建议大家不要用了!

  • 相关阅读:
    django+uwsgi+nginx实现负载均衡
    centos7 pip安装
    centos虚拟环境配置
    cenots7更换国内pip源
    FastDFS缩容
    FastDFS基于group扩容
    centos同步系统时间
    centos永久开放端口
    pip更换国内源
    Java四种访问修饰符
  • 原文地址:https://www.cnblogs.com/ash-sky/p/9620815.html
Copyright © 2011-2022 走看看