我似乎无法弄清楚为什么只有第一个元素调用我的事件处理程序来显示警报。我在Stack Overflow上找到了其他类似的问题,这些问题涉及使用ID而不是类,但这不是我的问题。
当我点击第一个元素旁边的“x”时,它按预期显示警报,但对于通过附加按钮动态添加的其他元素则无法实现。
这是一个最小但完整的示例:
<!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>
.live()
在1.7中已被弃用,即使在使用早期版本的jQuery的项目中,也不建议使用它。 - saluce