2009-08-07 61 views
0

仍然試圖找出慣用的jQuery - 這裏有一些用於設置div類的變量的jQuery - 有沒有一種更簡潔的jQuery方法,因爲div問題可能有不止一類...在jQuery中設置一個基於CSS類的變量

var currentType = 'component'; 
// text_component, image_component, tagged_component 
if ($(my_div).hasClass('.text_component')) { currentType = 'text_component' }; 
if ($(my_div).hasClass('.image_component')) { currentType = 'image_component' }; 
if ($(my_div).hasClass('.tagged_component')) { currentType = 'tagged_component' }; 

var dialog_box = $('div[id^='+currentType+'_dialog]'); 

回答

1

如果我弄明白了,我建議你使用由John Resig(jquery的創建者)編寫的metadata plugin,你可以在任何div元素上設置任何數據供以後使用。你不需要從CSS類獲取參數。您可以隨時閱讀這些數據。

樣品的標記:(從插件頁面)

<div class="someclass {some: 'data'} anotherclass">...</div> 

然後在javascript:

var data = $('div.someclass').metadata(); 
if (data.some == 'data') alert('It Worked!'); 

希望它能幫助,思南。

+0

現貨!這正是我尋找的東西......意味着我不必爲新的組件類添加測試。謝謝。 – Dycey 2009-08-07 18:25:50

+0

不客氣,這爲我節省了很多時間:) – Sinan 2009-08-07 23:08:44

0

當使用hasClass測試,不包括.(點)。

至於更簡單的方法,你可以縮短它,但使用hasClass可能是最好的方法。

我假設這些類有優先權(因此如果有多個類,那麼if系列中的後者優先於其他類)?或者你想支持多個「組件」?

下面是一個更有效的版本,顯示出較好的正在發生的事情:

var currentType, div = $(my_div); 
// text_component, image_component, tagged_component 
if (div.hasClass('tagged_component')) currentType = 'tagged_component'; 
else if (div.hasClass('image_component')) currentType = 'image_component'; 
else if (div.hasClass('text_component')) currentType = 'text_component'; 
else currentType = 'component'; 

var dialog_box = $('div[id^='+currentType+'_dialog]'); 
+0

非常感謝'。'的領導。 – Dycey 2009-08-07 12:39:59

2
currentType = $(my_div).attr("class"); 

將分配無論是在類的屬性,因此也處理超過一類

如果以後你可能想要做個別檢查,你可以將這些類拆分成一個單獨的類值的數組......像這樣:

var classes = currentType.split(' '); //return an array of separate class values 
+0

是的,但目的是能夠立即使用currentType來獲得適當的(隱藏的)對話框div。在這種情況下,我將不得不添加某種檢查(例如'text_component')是否在數組中。或者我錯過了什麼? – Dycey 2009-08-07 12:39:01

相關問題