如下
問題
剛開始two是隱藏的,點擊one對應的two會顯示,第一次點擊two的時候,只會跳出一個alert(),重復點擊就會遞增的alrt(), 2次,3次......
圖片
代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.one {
height: 100px;
border-bottom: 1px solid #000;
}
.two {
display: none;
width: 50px;
height: 20px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="box">
<div class="box-item">
<div class="one">
one
<div class="two">two</div>
</div>
</div>
<div class="box-item">
<div class="one">
one
<div class="two">two</div>
</div>
</div>
<div class="box-item">
<div class="one">
one
<div class="two">two</div>
</div>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$('.box .box-item .one').click(function() {
$(this).find(".two").show()
$(this).find(".two").click(function() {
alert($(this).html());
})
})
</script>
</body>
</html>
4 回答

侃侃爾雅
TA貢獻1801條經驗 獲得超16個贊
- 這不是冒泡,這是重復綁定。
- DOM里的事件是這樣的,你可以想象每個DOM結構有一張散列表,這張表一開始是空的,每次注冊一個事件回調呢,就會把這個回調記到這個表上;而事件發生的時候呢,就會找到這個表,然后一個回調一個回調的去執行。
- 有個常見的誤區,是以為每個DOM只有一個回調,事件發生時被觸發執行,這是不對的。事實上,注冊了一個回調就會執行一個,而注冊了好幾個,就會挨個執行。
- 題目中的錯誤也挺常見,是一個事件回調里邊注冊另一個事件回調,這樣當外邊的回調執行時,就會給里邊的DOM上掛一個回調,執行多次以后,里邊的回調也相應增多,這樣在觸發里邊DOM的時候,就會有多個回調被執行,從而導致錯誤。
- 原生寫法的注冊事件其實可以拒掉具名函數事件回調的重復注冊,但在jQ里,都是匿名函數/函數表達式,原生也防不住,從而變成了常見錯誤。

動漫人物
TA貢獻1815條經驗 獲得超10個贊
$(this).find(".two").click(function(e) {
e.stopPropagation();
alert($(this).html());
})

開心每一天1111
TA貢獻1836條經驗 獲得超13個贊
$('.box .box-item .one').click(function() {
$(this).find(".two").show()
$(this).find(".two").off();
$(this).find(".two").click(function() {
alert($(this).html());
})
})
- 4 回答
- 0 關注
- 474 瀏覽
添加回答
舉報
0/150
提交
取消