jQuery 事件处理程序仅适用于第一个元素

标签 jquery event-handling

我似乎无法弄清楚为什么只有第一个元素调用显示警报的事件处理程序。我在 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/

相关文章:

javascript - Jquery 数据表在 Internet Explorer 中显示为低亮度

Javascript修改元素事件函数的参数

android - 您可以使用 XML 将 View 连接到事件处理程序吗?

jquery - 每个() jQuery 中的 Change()

Javascript循环对象并操作

jQuery - 检查类是否存在,如果不破坏函数

javascript - 旋转时触发不透明度,jquery

javascript - 支持 eventData 的 jQuery .toggle() 方法的替代方法?

javascript - 删除自定义事件监听器

vba - 在工作簿的任何工作表中保存最后更改/修改的代码不准确