我似乎無法弄清楚爲什麼只有第一個元素調用顯示警報的事件處理程序。我發現堆棧溢出的其他類似問題與使用ID而不是類有關,但這不是我的問題。jQuery事件處理程序只適用於第一個元素
當我點擊第一個元素旁邊的'x'時,它將按預期方式顯示警報,但未能爲通過追加按鈕動態添加的其他元素執行此操作。
這裏有一個最小的,但完整的例子:
$("a.test").click(function() {
到
$("a.test").live('click', function() {
爲什麼只有第一個元素是工作的原因是因爲當時
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$(".append").click(function(){
$('.container').append('<div class="box"></div>')
$('.box:last').append('<div class="text"><span>ABCDEFG</span><br/></div>')
$('.box:last').append('<a href="#" class="test">x</a>')
});
$("a.test").click(function() {
alert("works only for the first item in the list");
});
});
});
</script>
<style>
.box {
padding:3px;
margin-bottom:3px;
border-bottom:2px solid #fff;
width:550px;
}
.box:hover{background-color:#fff;}
#container {
position:relative;
}
.text {
float:left;
width:300px;
font-size:13px;
}
.text span {
font-size:18px;
line-height:23px;
font-weight:700;
}
</style>
</head>
<body>
<div class="container">
<input type="button" class="append" value="Append">
<div class="box">
<div class="text"><span>ABCDEFG</span></div>
<a href="#" class="test">x</a>
</div>
</div>
</body>
</html>
就是這樣。我正在學習jQuery,並被這個問題困擾了幾天。感謝您提供清晰,簡潔的答案。 – Raj 2011-03-27 14:18:18
'.live()'在1.7中被棄用,即使在使用舊版jQuery的項目中也不鼓勵它的使用。 – saluce 2012-07-30 16:00:41
@saluce - 好點,但是當我寫這個答案的時候,「活着」真是充滿活力和繁榮。 – Anurag 2012-07-30 17:32:42