我正在通过脚本(Smarty)动态生成下拉列表。
如果下拉列表只有一个选项值,是否可以将其显示为标签。
这将显示一个包含3个值的下拉列表。
<select>
<option> 1 </option>
<option> 2 </option>
<option> 3 </option>
</select>
如果它只显示一个值然后将其显示为标签,是否可以使用纯HTML或Jquery或两者的组合?我可以使用smarty检查值并抛出不同的不同html,但这会使我的代码变长,因为我有很多下拉。
<select>
<option> 1 </option>
</select>
我可能缺少任何简单的逻辑吗?
更新(已解决)
感谢所有帮助过的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());
});
}
});
答案 0 :(得分:3)
$('select').each(function(){
if($(this).find('option').length === 1){
$(this).replaceWith(function(){
return $('<label />').html($(this).text());
});
}
});
生成下拉列表后,您只需运行此代码段即可检查每个select
元素。
答案 1 :(得分:1)
我会迭代每个<select>
元素,检查它们的选项数量,并相应地进行所需的DOM更改:
$('select').each(function(index, select) {
var numOptions = $('option', this).length;
if(numOptions === 1) {
// replace the select element here - something like the below
var label = $('<label>').html(this.value);
$(this).after(label).hide();
}
});
我选择隐藏而不是替换<select>
元素,因此您仍然可以获取作为表单一部分发回的值。如果不需要,则可以使用.remove()
代替.hide()
完全删除元素。