我正在通過腳本(Smarty)動態生成下拉列表。HTML,顯示標籤如果下拉只有一個值
如果下拉菜單中只有一個選項值,是否可以將其顯示爲標籤。
這將顯示一個包含3個值的下拉菜單。
<select>
<option> 1 </option>
<option> 2 </option>
<option> 3 </option>
</select>
如果它顯示然後只是一個值顯示爲標籤,是能夠以兩者的純HTML或Jquery的或組合?我可以使用smarty來檢查值並拋出不同的html,但這會讓我的代碼長久,因爲我有很多下拉菜單。
<select>
<option> 1 </option>
</select>
任何簡單的邏輯,我可能會失蹤?
UPDATE(解決)
感謝所有誰幫助stackoverflow'ers。 我使用@ahren給出的代碼,根據需要工作。
您已經生成您的下拉菜單後,但是我已經擴大代碼一個標籤的屬性複製到另一個,萬一要是有人找
// To replace a <select>, with <label> tag if it has just one value
$('select').each(function(){
if($(this).find('option').length === 1){
// Copy all attributes from a given tag and save it in a variable.
var attributes_from = $(this).prop("attributes");
var attributes_to = '';
$.each(attributes_from, function() {
attributes_to += ' '+this.name+'="'+this.value+'"';
});
// If select then copy its value from option.
attributes_to += ' value="'+$(this).find('option').attr('value')+'"';
// Replace the <tag>
$(this).replaceWith(function(){
return $('<label '+attributes_to+' />').html($(this).text());
});
}
});
非常感謝這麼一個小巧而智能的功能,在這7行代碼中一直在摸索着我的頭腦。 – 2013-03-21 14:31:32