我似乎无法弄清楚为什么只有第一个元素调用显示警报的事件处理程序。我发现堆栈溢出的其他类似问题与使用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