事件绑定:
(1)on:普通绑定事件
- <ul>
- <li>111li>
- <li>222li>
- <li>333li>
- ul>
- <script>
- $("ul li").on("click",function(){
- console.log("li click")
- })
- script>
结果:点一次li就打印一次”li click“
(2)on:事件委托的作用
on的事件委托的作用就是,可以传参数指定点击对象,当点击该对象时才能触发事件;
格式:选取标签.on(事件,要点击的东西,回调函数({要执行的代码}))
- <ul>
- <li>111
- <button>deletebutton>
- li>
- <li>222
- <button>deletebutton>
- li>
- <li>333
- <button>deletebutton>
- li>
- ul>
- <script>
- $("ul").on("click","button",function(){
- console.log("ul click")
- })
- script>
结果:点delete会触发ul事件,打印ul click;当点击li不会触发ul事件
(3)on--传参数的用法:
- <ul>
- <li>111
- <button>deletebutton>
- li>
- <li>222
- <button>deletebutton>
- li>
- <li>333
- <button>deletebutton>
- li>
- ul>
- <script>
- $("ul").on("click",{name:"yiyi"},function(e){
- console.log(e)
- })
- script>
结果:
(4)on--事件委托+传对象参数
- <ul>
- <li>111
- <button>deletebutton>
- li>
- <li>222
- <button>deletebutton>
- li>
- <li>333
- <button>deletebutton>
- li>
- ul>
- <script>
- $("ul").on("click","button","hello",function(e){
- console.log(e)
- })
- script>
结果:
- <ul>
- <li>111
- <button>deletebutton>
- li>
- <li>222
- <button>deletebutton>
- li>
- <li>333
- <button>deletebutton>
- li>
- ul>
- <script>
- $("ul li").click(function(){
- console.log("click")
- })
- script>
- $("ul li").click(function(){
- console.log("click")
- }).mouseover(function(){
- console.log("mouseover")
- })
-
- function A(){
- console.log("AAA")
- }
- function B(){
- console.log("BBB")
- }
- $("ul li").on("click",A).on("click",B)
- $("ul li").off("click",A)
-
- document.onclick = function(){
- console.log("1111")
- }
- $(document).click(function(){
- console.log("1111")
- })