【问题标题】:HTML, display label if drop down has just one valueHTML,如果下拉菜单只有一个值,则显示标签
【发布时间】:2013-03-10 19:15:18
【问题描述】:

我正在通过脚本 (Smarty) 动态生成下拉列表。

如果下拉菜单只有一个选项值,是否可以将其显示为标签。

这将显示一个包含 3 个值的下拉列表。

<select>
    <option> 1 </option>
    <option> 2 </option>
    <option> 3 </option>
</select>

如果它只显示一个值然后将其显示为标签,是否可以使用纯 HTML 或 Jquery 或两者的组合?我可以使用 smarty 来检查值并抛出不同的 html,但这会使我的代码只要我有很多下拉菜单。

<select>
    <option> 1 </option>
</select>

任何我可能遗漏的简单逻辑?

更新(已解决)

感谢所有提供帮助的 stackoverflow 人员。 我使用了@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());
        });
    }
});

【问题讨论】:

    标签: jquery html smarty option html-select


    【解决方案1】:
    $('select').each(function(){
      if($(this).find('option').length === 1){
        $(this).replaceWith(function(){
           return $('<label />').html($(this).text());
        });
      }
    });
    

    生成下拉列表后,您只需运行此 sn-p 即可检查每个 select 元素。

    演示:http://jsfiddle.net/kqunE/

    【讨论】:

    • 非常感谢这么小而智能的功能,这 7 行代码让我头疼了一天。
    【解决方案2】:

    我会遍历每个 &lt;select&gt; 元素,检查它们拥有的选项数量,并相应地进行所需的 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();
        }
    });
    

    我选择隐藏而不是替换 &lt;select&gt; 元素,因此您仍然可以将值作为表单的一部分发回。如果不需要,那么您可以使用 .remove() 代替 .hide() 完全删除该元素。

    【讨论】:

    • 嗨,@Anthony 也感谢您的帮助,尚未测试您的代码,但它似乎遵循与 (at)ahren 的代码相同的逻辑步骤,它应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多