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

  • 相关阅读:
    CF1051F The Shortest Statement
    [ZJOI2006]书架
    [FJOI2007]轮状病毒
    CF147B Smile House
    HDU4415 Assassin’s Creed
    飞行员配对方案问题
    [NOI2005]瑰丽华尔兹
    [NOIP2016]换教室
    [国家集训队]部落战争
    [NOI2005]聪聪与可可
  • 原文地址:https://www.cnblogs.com/ash-sky/p/9620815.html
Copyright © 2011-2022 走看看