简体   繁体   English

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

[英]jQuery event handler only works for first element

I can't seem to figure out why only the first element invokes my event handler that displays an alert. 我似乎无法弄清楚为什么只有第一个元素调用显示警报的事件处理程序。 I found other similar questions on Stack Overflow that related to using IDs rather than classes, but that's not my issue. 我在Stack Overflow上发现了其他与使用ID而不是类相关的类似问题,但这不是我的问题。

When I click on the 'x' next to the first element it displays the alert as expected, but fails to do so for the other elements that were added dynamically with the append button. 当我单击第一个元素旁边的“ x”时,它会按预期显示警报,但对于使用附加按钮动态添加的其他元素却没有显示警告。

Here's a minimal, but complete example: 这是一个最小但完整的示例:

<!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>

Your event handler isn't being added to subsequently appended elements. 您的事件处理程序不会被添加到后续添加的元素中。 There are several ways to attach the event handler dynamically. 有几种方法可以动态地附加事件处理程序。 For newer versions of jQuery (1.7+), use the .on() function with a selector. 对于较新版本的jQuery(1.7+),请将.on()函数与选择器一起使用。

$('.container').on('click', 'a.live', function() { alert("I'm on"); });

Older versions of jQuery don't have .on() , so you can use .live() . 较旧版本的jQuery没有.on() ,因此您可以使用.live() However, one caveat is that .live() is deprecated in 1.7. 但是,有一点需要注意的是,1.7中不推荐使用.live()

$('a.live').live('click', function() { alert("I'm live"); });

Even the jQuery team suggests using alternatives to .live() , regardless of the version of jQuery you are using. 甚至jQuery团队也建议使用.live()替代方法,而不管您使用的是哪个jQuery版本。 For versions older than 1.7, use .delegate() . 对于1.7之前的版本,请使用.delegate()

$('.container').delegate('a.test', 'click', function() { alert("I'm delegated"); });

change 更改

$("a.test").click(function() {

to

$("a.test").live('click', function() {

The reason why only the first element is working is because at the time the click event is attached, there is only one <a> element on the page. 之所以只有第一个元素起作用,是因为在附加click事件时,页面上只有一个<a>元素。 You need to explicitly add the click event handler to every anchor that is created, or use live events instead. 您需要将click事件处理程序显式添加到创建的每个锚点,或者改用实时事件。 Read more about live event handlers. 了解有关live事件处理程序的更多信息。

When you hook up event handlers with bind ( click is a shortcut for bind("click", ...) ), only elements that already exist are hooked up. 当您使用bind连接事件处理程序时( clickbind("click", ...)的快捷方式),仅连接已经存在的元素。 New ones you add later are not. 以后添加的新文件不是。

You can use the live or delegate function, or the delegation features of the on function, or hook them up individually when you add them: 您可以使用live delegate功能,或on函数的delegate功能,也可以在添加它们时分别将它们挂钩:

  • Live example - Using the latest jQuery and delegate (you can also use on , but I like how delegate documents my intent): 实时示例 -使用最新的jQuery和delegate (您也可以on使用,但我喜欢delegate记录我的意图的方式):

     jQuery(function($) { $("#theButton").click(function() { $("#container").append( "<div><a class='test' href='#'>X</a></div>" ); }); $("#container").delegate("a.test", "click", function() { alert("Clicked"); }); }); 
  • Live example - Using the latest jQuery and on (note that the order of arguments is different from delegate ): 活生生的例子 -使用最新的jQuery和on (注意,参数的顺序是不同的delegate ):

     jQuery(function($) { $("#theButton").click(function() { $("#container").append( "<div><a class='test' href='#'>X</a></div>" ); }); $("#container").on("click", "a.test", function() { alert("Clicked"); }); }); 
  • Live example - Using your jQuery vesion (1.3.0?!) and hooking them up as you add them: 实时示例 -使用jQuery vesion (1.3.0 ?!)并在添加它们时将它们连接起来:

     jQuery(function($) { $("#theButton").click(function() { $("<div><a class='test' href='#'>X</a></div>") .click(aTestClick) .appendTo("#container"); }); $("a.test").click(aTestClick); function aTestClick() { alert("Clicked"); } }); 

Off-topic (slightly): 离题(略):

  1. jQuery 1.3.0 is nine releases and more than two years out of date. jQuery 1.3.0有九个版本,并且已经过了两年以上。 Current release (as of the original answer, March 2011) is 1.5.1, and even if you want to stick with the 1.3 tree, there were not one but two maintenance releases after 1.3.0. 当前版本(截至原始答案,2011年3月)是1.5.1,即使您要坚持使用1.3树,在1.3.0之后也没有一个,只有两个维护版本。
  2. You're using two separate ready calls, first the explicit one, then an implicit one (your $ where you pass in a function). 您正在使用两个单独的ready调用,首先是显式调用,然后是隐式调用(在函数中传递的$ )。 Only one is necessary. 只需要一个。
  3. Strongly recommend not relying on semicolon insertion, it's the spawn of the devil. 强烈建议不要依赖分号插入,这是魔鬼的产物。 End your statements with semicolons, to ensure scripts can be minified/compressed/packed and just because the interpreter can guess wrong sometimes. 以分号结尾的语句,以确保可以缩小/压缩/打包脚本,并且仅因为解释器有时会猜错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM