更改所选项目的文本以包括其父级optgroup

时间:2012-07-05 04:09:37

标签: javascript jquery html

我有一个select元素,将在移动设备上显示

<form>
<select id="selectMe" >
    <optgroup label="Australia">
        <option value="AustCars">Australia Cars Report</option>
        <option value="AustBikes">Australia Bikes Report</option>                
    </optgroup>
    <optgroup label="New Zealand">                    
        <option value="NZCars">New Zealand Cars Report</option>
        <option value="NZBikes">New Zealand Bikes Report</option>                
    </optgroup>
</select>
</form>​

有两点需要注意:

  • 我希望在关闭时显示全名Australia Cars Report,以消除澳大利亚和新西兰之间的歧义。
  • 我想在Cars Report打开时使用较短的版本select,因为iPhone选择器的全名Australia Cars Report太长了(不是实际名称,而是呈现为{ {1}}或类似的国家/地区隐含在Austr...rs Report

我的方法(基于Change a select list display value upon selecting description)是在控件获得焦点时修改每个项的值,然后在失去焦点时取消修改。这就是我被卡住的地方。

我有两个问题:

  • 我可以得到焦点事件,但没有'lostfocus'事件。我无法使用'已更改'事件,因为用户可能实际上没有更改选择。
  • 我不知道如何从选项文本中添加和删除optgroup的值。我的意思是,我需要找到optgroup,它嵌套在Australia Cars Report下,因此我可以从显示文字中删除该字。

我可以使用javascript或jQuery或其他工具(如果适用)。开放给我提供一个简单的方法,我也忽略了这一点。

3 个答案:

答案 0 :(得分:1)

  

我可以获得焦点事件,但没有'lostfocus'事件。我无法使用'已更改'事件,因为用户可能实际上没有更改选择。

使用blur

  

我不知道如何从选项文本中添加和删除optgroup的值。

有点不清楚,但我会冒一些猜测让你开始:

  • 您需要为特定组提供唯一的ID才能访问它,例如

    var fooElement = document.getElementById("foo")

  • 您可以使用fooElement.selected
  • 获取所选对象
  • 您可以使用fooElement.options[]获取所有选项。在此列表中添加和删除新的DOM元素将在HTML DOM中添加或删除它们。
  • 可以使用option.value找到.text的值。

尝试在HTML中查找select标记,并使用javascript与该类型的元素进行交互。祝你好运。

答案 1 :(得分:1)

对于第一个问题:请参阅Steve的回复。

第二个问题: 当模糊时,您可以将文本澳大利亚添加到选项中

$("select").blur(function(){
   $(this).html($(this).parent().html() + " " + $(this).html());
});

答案 2 :(得分:1)

$('#selectMe option').click(function(){
    var myparent = $(this).parent();
    if (myparent.get(0).tagName == 'OPTGROUP'){
        $(this).text(myparent.attr('label') + ' ' + $(this).text());
    }
});

$('#selectMe').focus(function(){
    $('option', this).each(function(){
        var myparent = $(this).parent();    
        $(this).text($(this).text().replace(myparent.attr('label'),''));     
    });
})

在这里工作演示http://jsfiddle.net/GXvJB/11/

相关问题