最近的項目中有這么一個需求,點擊一排圖片中的任意一張后底部彈出一個對話框,要求點擊任意地方隱藏對話框
這個時候用not()顯然是不現實的,用closest()可以實現差不多的功能
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>選擇指定元素外的其他所有元素</title> <style> *{ margin: 0; padding: 0; } .box{ border: 1px solid red; overflow: hidden; } .box > div{ height: 100px; width: 100px; background-color: cadetblue; float: left; margin-left: 10px; } .box > div > div{ height: 50px; width: 50px; background-color: coral; } </style> </head> <body> <div class="box"> <div class="num1"> <div></div> </div> <div class="num2"> <div></div> </div> <div class="num3"> <div></div> </div> </div> <script type="text/javascript" src="js/jquery-1.11.0.js" ></script> <script> $(document).click(function(e){ if( $(e.target).closest('.num2').length == 0 ){ alert("事件觸發"); } }); </script> </body> </html>
關鍵知識點:jquery closest()
closest():在DOM樹中從當前元素開始向上尋找(包括當前元素),並用匹配元素構建一個新的jquery對象
參考:http://www.w3school.com.cn/jquery/traversing_closest.asp
