【问题标题】:Change text of selected option only while selected仅在选择时更改所选选项的文本
【发布时间】:2013-09-11 04:52:56
【问题描述】:

我有一个选择框,允许用户为一件衣服选择一个类别。类别可以有子类别,因此为了显示该层次结构,我编写如下选项:

Category Name
  ├─ Sub-category name

看起来像这样:

类别名称

  ├─ 子类别名称

不幸的是,当用户选择一个子类别时,选择框中显示的文本包括结构字符。如何仅在选择选项时显示类别名称,但在更改选项时保留结构 HTML?有没有更好的方法来显示选项中的类别层次结构? Optgroups 对我不起作用,因为用户还需要能够选择顶级类别。

这就是它现在的样子。

http://jsfiddle.net/K6yfp/

【问题讨论】:

  • 请添加一个 JS Fiddle!
  • 不要使用选择元素。
  • JS Fiddle 添加。 @epascarello 我会添加什么?该网站需要适合移动设备。
  • 你可以改为使用 optgroup 标签。
  • optgroups 不能解决问题,因为我需要顶级类别也是可选选项。

标签: javascript jquery html css django


【解决方案1】:

也许你正在寻找optgroup

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

FIDDLE

【讨论】:

  • Optgroups look 符合我的需要,但它们不可选择。在此示例中,我还需要选择“瑞典汽车”和“德国汽车”。
【解决方案2】:

我想出了一个简单的解决方案,但无法进一步锻炼。希望对您有所帮助。

HTML

<select id="Categories">
    <option value="Shoes">Shoes</option>
    <option value="Sneakers">&nbsp;&nbsp;&#x251c;&#x2500;Sneakers</option>
</select>

JS

$(document).ready(function(){
    var SelectedCategory = $('#Categories').find('option:selected').val();
    $('#Categories').bind("change",function() {
        $(this).find('option:selected').attr('label',$(this).find('option:selected').val());
        SelectedCategory = $(this).find('option:selected').val();
        $(this).blur();
    });

    $('#Categories').focus(function(e){
        e.stopPropagation();
        $(this).find('option:selected').removeAttr('label');
    }).blur(function(e){
        e.stopPropagation();
        $(this).find('option:selected').attr('label',$(this).find('option:selected').val());
    });
});

注意:不要忘记包含 jQuery 库。

检查Demo Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    相关资源
    最近更新 更多