jQuery-给ul添加了li之后,添加的li并没有绑定点击监听怎么办?
生活随笔
收集整理的這篇文章主要介紹了
jQuery-给ul添加了li之后,添加的li并没有绑定点击监听怎么办?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們看一個簡單的例子
效果圖如下
這里面有一個ul里面套著4個li,還有一個獨立的li
代碼實例:
需求
1.點擊li,背景就會變成紅色
2.點擊btn,就會添加一個li
效果如下:
我們會發現,添加之后的li點擊了沒有變化,說明添加之后的li并沒有綁定點擊監聽
解決方法一(普通方法):
<html><head><base href="<%=basePath%>"><title>My JSP 'practice_02.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><style type="text/css"></style></head><body> <ul><li>111</li><li>222</li><li>333</li><li>444</li></ul><li>222</li><button id="btn">添加一個li</button><script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script><script type="text/javascript">//1.點擊li,背景就會變成紅色$('ul>li').click(function() {//第一種寫法this.style.background = 'red';//第二種寫法 $(this).css('background','red');});//2.點擊btn,就會添加一個li$('#btn').click(function() {$('ul').append('<li>222</li>')//這里我們會發現,當我們添加了一個li之后,點擊它背景顏色并不會改變.children('li')//找到ul的孩子li.click(function() {//添加點擊事件this.style.background = 'red';});});</script></body> </html>方法二(事件委托):
1.簡單講解
(1)事件委托(代理/委派):
->將多個子元素(li)的事件監聽委托給父輩元素(ul)處理
->監聽回調是加在了父輩元素上
->當操作任何一個子元素(li)時,事件會冒泡到父輩元素(ul)
->父輩元素不會直接處理事件,而是根據event.target得到發生事件的子元素(li),通過這個子元素調用事件回調函數
(2)事件委托的雙方
->委托方: 業主li
->被委托方: 中介ul
(3)使用事件委托的好處
->添加新的子元素,自動有事件響應處理
->減少事件監聽的數量
(4)jQuery事件委托API
->設置事件委托:$(parentSelector).delegate(childrenSelector,eventName,callback)
->移出事件委托:$(parentSelector).undelegate(eventName)
2.代碼實例
<html><head><base href="<%=basePath%>"><title>My JSP 'practice_02.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><style type="text/css"></style></head><body> <ul><li>111</li><li>222</li><li>333</li><li>444</li></ul><li>222</li><button id="btn">添加一個li</button><script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script><script type="text/javascript">//1.點擊li,背景就會變成紅色$('ul>li').click(function() {//第一種寫法this.style.background = 'red';//第二種寫法 $(this).css('background','red');});//2.點擊btn,就會添加一個li$('#btn').click(function() {$('ul').append('<li>222</li>');});//事件委托$('ul').delegate('li','click',function() {this.style.background = 'red';});</script></body> </html>3.效果
請讀者復制代碼自行測試
總結
以上是生活随笔為你收集整理的jQuery-给ul添加了li之后,添加的li并没有绑定点击监听怎么办?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在servlet中设置的字符编码集为什么
- 下一篇: jQuery-事件委托(基本概述+实例)