5

我有以下代码:

JS:

var test2 = ['RMrpi5Z8doc','JIPbUaqyYx0','MbjXYg0YRmw'];

    $('tr').live('click', function(event){
      $($(this).attr('class').split(' ')).each(function() { 
        if (!((this == 'even') || (this == 'odd'))) {
            alert(jQuery.inArray(this, test2));
            if (this == 'RMrpi5Z8doc') {
              alert(this);
            }
        }   
      });
    });

HTML:

  <table>
   <tr class="odd RMrpi5Z8doc">
     <td>Kite</td>
     <td>Just Like Vinyl</td>
     <td>Audiotree</td>
   </tr>
  </table>

inArray 不匹配并返回 -1。匹配文字字符串的 if 语句确实匹配。如果我用 inArray 中的文字替换,那也匹配。

我看过一篇文章说 jQuery attr 不再返回字符串,但是查看 jQuery 站点上的 attr 文档似乎说它确实如此。

也许我应该以完全不同的方式解决这个问题?

4

3 回答 3

5

你用错了each。你的意思是jQuery.each,通用迭代器:

$.each($(this).attr('class').split(' '), function ...);

不是each,jQuery 实例上的实例函数:

$($(this).attr('class').split(' ')).each(function ...); // Wrong

特别是,正在发生的是上面的这一部分:

$($(this).attr('class').split(' '))

...调用$()数组,它不会做你想做的事。:-)

于 2012-10-22T13:56:52.637 回答
1

我已经使用以下方法重构了它:

$(document).on('click', 'tr', function(){
  alert(jQuery.inArray($(this).attr('id'), test2));
}

这似乎有效。我已将类名移至 id 字段,因为我没有将这些标识符用于任何样式表,它们确实是 id。

于 2012-10-22T14:42:04.400 回答
0

这确实是类型不匹配。如果您切换到if (this === 'RMrpi5Z8doc') {,第二个警报将不再触发。使用this.toString()将解决此问题,如下所示:

$.each($(this).attr('class').split(' '), function() { 
    //...etc.

顺便说一句,这是一种不寻常的做法。通常,您将使用以下方法测试一个类hasClass

$('tr').on('click', function() {
    if ($(this).hasClass('odd')) {
        //...

此外,正如 raina77ow 所指出的,还有:even:odd伪类:

$('tr').on('click', function() {
    if ($(this).is(':odd')) {
        //...

这样,您可以完全省去您的oddeven课程。

于 2012-10-22T14:33:03.410 回答