jQuery只返回第一项

时间:2010-05-13 15:46:50

标签: jquery jquery-selectors

由于一些奇怪的原因,每当我有一个选择器并期望获得多个项目时,jQuery只返回第一个项目,而不是整个集合。

这是我的HTML:

<a id="reply-424880" class="reply" href="#" rel="nofollow">Reply</a>
<a id="reply-424885" class="reply" href="#" rel="nofollow">Reply</a>

选择器:

$('.reply').unbind('click').click(function(event) {
 ...
}

我尝试使用FireBug进行调试,但仍然得到相同的结果。使用我的工作可以让它工作:

$('a').each(function (index, element) {
            if ($(element).attr('class') == 'reply') {
                $(this).unbind('click').click(function(event) {
                     ...
                });
             }
});

我想使用内置功能而不是我的工作。知道为什么只返回第一个元素吗?

4 个答案:

答案 0 :(得分:20)

尴尬的是,我也遇到了这个问题,结果证明Chrome似乎有一个类似于$()jquery的函数,它以类似的方式实现了一个选择器逻辑的子集,但缺少一堆函数:

> $
function $(selector, [startNode]) { [Command Line API] }

正确包含jQuery的Vs:

> $
function (e,n){return new x.fn.init(e,n,t)} 

所以..是的,事实证明我的脚本标签有点格式错误 - 不足以导致任何错误,它仍然获取了jQuery文件,因此网络视图仍然显示它被提取,它只是不是那时解释为javascript,因此缺少jQuery,但足够的语法仍然有效,它让我扔了很长时间。

希望这会在某个时候节省一些时间。

答案 1 :(得分:3)

你所拥有的东西应该已经工作,you can see an example here,这是一个简单的电话:

$('.reply').unbind('click').click(function(event) {
  alert('hi there');
});​

如果没有为所有这些处理程序执行相同的处理程序,那么您必须在问题之外有一些影响链接的内容。如果您从第一个开始只获得attribute,请确保您的功能内部没有像$(".reply").attr("id")这样的内容,您应该在处理程序中使用this,而不是$('.reply').unbind('click').click(function(event) { alert($('.reply').attr("id")); //alerts "reply-424880" for both });​ 。 ll从匹配的第一个元素中获取属性。

Here's an example

$('.reply').unbind('click').click(function(event) {
  alert($(this).attr("id")); //alerts "reply-424880" for both
  //and use just this.id in this case, no need for jQuery .attr(), like this
  //alert(this.id);
});​

It should be like this

{{1}}

答案 2 :(得分:1)

在将解决方法保留几个月之后,我决定尝试查看页面上是否有任何导致问题的内容。

通过消除过程,我能够将错误范围缩小到jquery.validate.js文件。由于某些未知原因,此文件导致jQuery仅返回第一个值。我下载了最新版本,选择器现在返回 all 匹配的元素。

答案 3 :(得分:0)

这应该有效但是......

$('.reply').each(function() { 
   $(this).unbind('click').click(function(event) {
      ... 
   });
});
相关问题