2012-10-22 77 views
3

我有以下代碼:jQuery attr似乎不返回字符串?

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的文檔似乎是這樣說的。

也許我應該以完全不同的方式來談論這個?

+1

你想達到什麼目的? –

+2

*「也許我應該採取完全不同的方式?」*我建議不要使用class來存儲這個值。你可以使用'data-id',或者如果它們是唯一的,'id'應該可以工作。 –

+2

雖然您正在考慮重新編寫代碼,但請注意'.live()'已被棄用一段時間了。如果你使用最新的jQuery,你應該使用'.on()'API。 – Pointy

回答

5

您使用的是錯誤的each。你的意思jQuery.each,通用迭代器:

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

each,jQuery的實例的實例功能

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

特別是發生了什麼事是上面的這部分:

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

...調用$()與數組,它不會做你想做的事情。 :-)

+2

...或者只是'$ .each(this.className.split(''),function ...)' – raina77ow

+3

@ raina77ow:的確,我只做了很小的改動,但我絕對主張在屬性可靠時使用直接反射屬性('this.className'而不是'$(this).attr('class')'') (和'className'是)。 –

+0

另外'.attr(「class」)'在舊版本的IE中不起作用,我不這麼認爲。 – Pointy

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')) { 
     //... 

通過這種方式,你可以用你的odd免除和even類完全。

1

我重構這個使用:

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

這似乎工作。我將類名移到了id字段,因爲我沒有將這些標識符用於任何樣式表,它們確實是id。