jQuery:not()选择器没有工作的类

时间:2014-06-27 20:54:42

标签: jquery jquery-selectors

我有以下HTML:

<ul> 
    <li>Hello</li>      
    <li>World</li>
    <li class="not_me">Hi</li>
</ul>

我希望在一个jQuery调用中将列表项中的所有文本作为数组:

arr = $('li:not(.not_me)').map(function(el, i) {
    return $(el).text();
});

预期结果:

  
    

arr = ['你好','世界']

  

实际结果:

  
    

arr = ['你好','世界','你好']

  

为什么我的:not()排除不起作用?用引号“not('。not_me')”写出它会得到相同的结果。

这是一个显示问题的JSFiddle: http://jsfiddle.net/cC8fT/683/

2 个答案:

答案 0 :(得分:2)

这有效fiddle

arr = $.each($('li:not(.not_me)'), function(i, el) {
    return el;
});

选择器$('li:not(.not_me)')为您提供数组,然后$.each()遍历所有内容。在该示例中,您可以看到带有新元素的新元素块。

您可以做很多事情,例如,如果您只想要名字,可以这样做:

var arr = [];
$.each($('li:not(.not_me)'), function(i, el) {
   arr.push($(el).val()); // or text
});

有时你必须接受你不能也不应该在一行中做事:)。要么它太复杂,要么使你的代码不可读。

<强> 修改

刚发现对于$.each,迭代器函数需要有index然后element而不是其他方式

答案 1 :(得分:1)

:not运算符工作正常,但代码中还存在其他一些问题。

您已交换了eli参数,因此该元素位于i参数中,索引位于el参数中。

结果不是数组,它是包含数组的jQuery对象。您可以使用get方法将数组从对象中取出。

var arr = $('li:not(.not_me)').map(function(i, el) {
  return $(el).text();
}).get();

演示:http://jsfiddle.net/P8uS6/

相关问题