我正在通过脚本(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