我有一个 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
,以消除澳大利亚和新西兰之间的歧义。 - 我想在打开
select
时使用较短的版本Cars Report
,因为全名Australia Cars Report
太长了iPhone 选择器(不是实际名称,而是呈现为Austr...rs Report
或类似名称)并且国家隐含在optgroup
中。
我的方法(基于 Change a select list display value upon selecting description )是在控件获得焦点时修改每个项目的值,然后在失去焦点时取消修改。这就是我遇到困难的地方。
这里有两个问题:
- 我可以获得焦点事件,但没有“失去焦点”事件。我无法使用“已更改”事件,因为用户可能实际上并未更改选择。
- 我不知道如何获取
optgroup
的值以在选项文本中添加和删除。我的意思是,对于Australia Cars Report
,我需要找到它嵌套在Australia
下,因此我可以从显示文本中删除该词。
我可以使用 javascript 或 jQuery,或者其他适用的工具。乐于接受我也忽略了的简单方法的建议。
最佳答案
I can get the focus event, but there's not 'lostfocus' event. I can't use the 'changed' event because the user might not have actually changed the selection.
使用模糊
。
I don't know how to get the value of the optgroup to add and remove from the option text.
有点不清楚,但我会大胆猜测一些以帮助您入门:
您需要为特定组提供一个 ID 以唯一地访问它,例如
var fooElement = document.getElementById("foo")
- 您可以使用
fooElement.selected
获取选中的对象 - 您可以使用
fooElement.options[]
获取所有选项。向此列表添加和删除新的 DOM 元素将在 HTML DOM 中添加或删除它们。 - 可以使用
.value
或.text
找到选项
的值。
尝试查找 HTML 中的 select
标记,以及与该类型元素交互的 javascript。祝你好运。
关于javascript - 更改所选项目的文本以包括其父 optgroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11337752/