我似乎无法弄清楚为什么只有第一个元素调用显示警报的事件处理程序。我在 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>
最佳答案
改变
$("a.test").click(function() {
至
$("a.test").live('click', function() {
之所以只有第一个元素起作用是因为当时click
事件已附,只有一个<a>
页面上的元素。您需要将单击事件处理程序显式添加到创建的每个 anchor ,或改用实时事件。了解更多关于 live
事件处理程序。
关于jQuery 事件处理程序仅适用于第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5447312/