2012-12-08 29 views
0

我對jQuery變量「this」的值有個疑問。

我花了如下一些示例代碼...

function blockHighlite() 
{ 
// alert ('block ' + $gCurrentClass + ' index ' + $gIndex); 

     $(this).data('bgcolor', $(this).css('border-color')); 
     $(this).css('border-color','rgba(255,128,0,.5)'); 
     $(this).css('border-color', $(this).data('bgcolor')); 
    }; 

此代碼工作正常到的HIGHlite元素邊框,但是當我恰克代碼指向這樣一個特定的元素,使用全局變量代表所選元素失敗。 我不理解「this」變量的用法嗎?變量$ gCurrentClass和$ gIndex只是我所選元素的類和索引。

function blockHighlite() 
{ 
    alert ('block ' + $gCurrentClass + ' index ' + $gIndex); 
     $gCurrentClass.eq[$gIndex].data('bgcolor', $gCurrentClass.eq[$gIndex].css('border-color')); 
     $gCurrentClass.eq[$gIndex].css('border-color','rgba(255,128,0,.5)'); 
     $gCurrentclass.eq[$gIndex].css('border-color', $gCurrentClass.eq[$gIndex].data('bgcolor')); 
    }; 

任何幫助將不勝感激。

+1

'this'不是一個jQuery變量,它是一個javascript關鍵字referrencing,在這種情況下,該方法被調用的元素。只是用一些隨機變量取代它,即使正確設置也不會工作,因爲沒有自動引用您的類或其他任何東西。 – adeneo

+1

你會在.eq之後使用圓括號,而不是方括號嗎? –

+0

如何使用'blockHighlite'? –

回答

1

假設$gCurrentClass包含一個表示類名的字符串,您需要將它作爲查詢選擇器傳遞給jQuery構造函數($)。請嘗試以下操作:

function blockHighlite() 
{ 
    alert ('block ' + $gCurrentClass + ' index ' + $gIndex); 
    $('.'+$gCurrentClass).eq($gIndex).data('bgcolor', $('.'+$gCurrentClass).eq($gIndex).css('border-color')); 
    $('.'+$gCurrentClass).eq($gIndex).css('border-color','rgba(255,128,0,.5)'); 
    $('.'+$gCurrentclass).eq($gIndex).css('border-color', $('.'+$gCurrentClass).eq($gIndex).data('bgcolor')); 
}; 
+0

似乎不太可能以'$'開頭的變量只包含一個字符串。通常它是一個jQuery對象引用。我想我們需要更多信息! – Madbreaks

+1

@Madbreaks變量$ gCurrentClass和$ gIndex只是我所選元素的類和索引.'這是來自OP。對我來說,這聽起來像一個字符串,而不是引用該類的jQuery對象。 – Ohgodwhy

+0

@Madbreaks請閱讀這個問題... – BenM