2010-12-18 172 views
0

我堅持這一點,需要一些幫助。我知道這個邏輯解決方案,但不知道如何將它翻譯成jQuery代碼(新手在這裏:))。任何建議或幫助非常感謝!jQuery的addClass元素基於屬性值

我需要添加一個css類(活動類)到一個標題屬性等於變量值的元素。所以,讓我們說我的變量currentElement ='偉大的一天'。頁面上還有一個標籤元素,其標題屬性爲「偉大的一天」,例如<a title='great day' href='#'>

用jQuery我想:在DOM中找到一個標籤currentElement ==標籤標題並添加css類。所以,理想情況下它應該找到一個標籤並將css類添加到它。

我想出了這樣的事情,但不工作:

/* set currentElement var to the src attribute 
    value of an a tag on the page 
    this works */ 
var currentElement = $('#greatLink'] img[src*=' + test + ']').attr('src'); 

/* now find an a tag on the page that has 
    the same title attribute as var currentElement 
    this does not work */ 
$("a[title ='+currentElement+']").addClass('selectedThumb'); 
+0

示例代碼中的一些語法錯誤(*第一部分*) – 2010-12-18 22:47:31

回答

8

我想你只需要改變你的選擇,而不是使用,你有嵌套的單引號雙引號:

$('a[ title=' + currentElement + ']').addClass('selectedThumb'); 

只需指出,選擇器中的屬性值不需要引用。例如

$('a[ title="foo" ]') 

相同

$('a[ title=foo ]') 

整個選擇器本身只是一個字符串。無論您是否引用上述示例中的值foo與結果無關。雖然引用價值可能看起來更「正確」,但由於沒有必要,我覺得離開它更容易。幾乎可以肯定的是,在你的問題中,如果你將字符串與變量值連接起來,它就不那麼令人困惑了。

+0

非常感謝您對此的提示和見解,非常感謝! – IntricatePixels 2010-12-18 23:05:43

1
$('a[title="' + currentElement + '"]').addClass('selectedThumb'); 
+0

感謝所有回覆,它們都是有效的!現在它可以工作。 – IntricatePixels 2010-12-18 23:02:27

1

嘗試

$("a[title ='"+currentElement+"']").addClass('selectedThumb'); 

注意額外的報價。

+1

哇。看起來我應該在發佈前刷新。 – rcravens 2010-12-18 22:38:48

0
$('[title='+currentElement+']').addClass('yourclass');