2013-06-05 18 views
0

當我創建一個jQuery UI元素(按鈕,例如),我不喜歡這樣寫道:在元素的屬性中設置選項?

<button class="Button" data-options='{ "text": false, "icons": { "primary": "ui-icon-arrowthick-1-n" } }'>Move Up</Button> 

我有些JS,看起來這通常就是.Button並提取data-options屬性爲JSON,然後創建按鈕傳遞選項。

我在想,如果jQuery UI有任何內置函數來完成這個呢?舉例來說,我希望能夠通過把選項的屬性在每個子按鈕設置在Buttonset內的按鈕選項:

<div class="Buttonset"> 
    <input type="radio" id="SortDirection_Ascending" name="SortDirection" value="Ascending" /> 
    <label for="SortDirection_Ascending" title="Ascending" data-options='{ "text": false, "icons": { "primary": "ui-icon-arrowthick-1-n" } }'>&nbsp;</label> 
    <input type="radio" id="SortDirection_Descending" name="SortDirection" value="Descending" /> 
    <label for="SortDirection_Descending" title="Descending" data-options='{ "text": false, "icons": { "primary": "ui-icon-arrowthick-1-s" } }'>&nbsp;</label> 
</div> 

但jQuery的不知道要應用的選項。我可以在JS中做這個,就像我使用按鈕(和其他小部件)一樣。但我很好奇,如果這已經支持一個不同的屬性。

澄清:

當我創建窗口小部件,我想知道是否jQuery的可以自動從元件的一個屬性提取窗口小部件的選項,並將其應用到小部件

<button class="Button" data-options='{ "text": false, "icons": { "primary": "ui-icon-arrowthick-1-n" } }'>Move Up</Button> 

<script type="text/javascript"> 
    $(".Button").button(); 
    /* jQuery saw that this element has a "data-options" attribute and automatically 
    * extracted the options from this attribute and applied them to the widget. */ 
</script> 
+2

還是你的問題還不清楚。您將能夠以JSON的身份訪問它們,是的。 :) –

+0

您的筆記「我有一些JS查找任何.Button」和「我無法爲Buttonset做這件事」似乎是矛盾的。你能解釋爲什麼你不能爲div做這件事嗎? –

+0

我想知道是否有一個特定的屬性名稱,我可以使用哪個jQuery檢查並應用其中包含的選項。 –

回答

0

jQuery的data()功能是用於連接數據到DOM元素製成: http://api.jquery.com/jQuery.data/

$(".Button").data('options') 

這從一個html元素中提取數據

http://jsfiddle.net/a5sVM/1/

+0

這並不回答我的問題,我不認爲。 –

+0

「我想知道jQuery是否可以自動從元素上的屬性中額外添加小部件的選項。」這正是數據所做的,請參閱我的更新回答 – Antoine

+0

正確...請參閱我的更新問題以進行澄清。同時閱讀dremme的答案 - 他們得到了我所問的。謝謝。 –

1

沒有一個屬性在DOM元素中,您可以設置來完成此操作。您將不得不使用您已經使用的方法,或者在按鈕上調用jquery ui .button()方法時設置選項。例如:

$('button').button({ 
    icons: { 
    primary: "ui-icon-locked" 
    } 
}); 

唯一的另一種方法是手動包含jquery-ui在調用.button()後執行的類和結構。例如:

<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button" aria-disabled="false"> 
    <span class="ui-button-icon-primary ui-icon ui-icon-locked"></span> 
    <span class="ui-button-text">Button with icon on the left</span> 
</button> 
+0

謝謝你理解我的問題。這就是我需要知道的一切(使用內置功能是不可能的)。 –

+0

只是爲了澄清,這個功能並沒有被構建到jquery-ui中,但似乎你已經構建了你需要的功能! :) – dremme

+0

是的,我只是不想重寫已經存在的東西。 –