我想将<option />
标签的文本内容分组。举个例子,我有以下标签:<option>8:00 (1 hour)</option>
,时间模式8:00
可以修改,括号中的文本(1 hour)
也可以修改。
我考虑实现以下操作:
<option>
<span>8:00</span>
<span> (1 hour)</span>
</option>
在 <option />
标签内放置 <span />
标签,仅用于字符串操作而非样式设计,这样做是否有害?
我想将<option />
标签的文本内容分组。举个例子,我有以下标签:<option>8:00 (1 hour)</option>
,时间模式8:00
可以修改,括号中的文本(1 hour)
也可以修改。
我考虑实现以下操作:
<option>
<span>8:00</span>
<span> (1 hour)</span>
</option>
在 <option />
标签内放置 <span />
标签,仅用于字符串操作而非样式设计,这样做是否有害?
根据HTML 5规范:
内容模型:
- 如果元素具有标签(label)属性和值(value)属性:没有任何内容。
- 如果元素具有标签(label)属性但没有值(value)属性:文本。
- 如果元素没有标签(label)属性且不是datalist元素的子元素:非元素间空格的文本。
- 如果元素没有标签(label)属性且是datalist元素的子元素:文本。
因此,取决于上下文,你可以在 <option>
元素中放置两个东西——文本或者什么都不放——不能放置 <span>
或其他任何元素。
根据 HTML 4.01 规范:
<!ELEMENT OPTION - O (#PCDATA) -- selectable choice -->
即使是HTML 3.2和HTML 2的规范都说:<!ELEMENT OPTION - O (#PCDATA)*>
选项元素不能有任何子元素。因此,是的,这是不好的。
<select>
转换成带有额外功能的<div>
块。如果你想这样做,最好使用HTML替代你的<select>
。
正如其他人所描述的那样,我已经尝试使用<b>和其他标签,但是<option>标签不支持其中嵌套标签。
解决方法是,虽然无法在<option>标签中使用<span>标签,但是可以通过索引号提取文本,例如document.getElementById(selectid).options[x].text,其中x是相关的索引号变量。
然后,您可以使用"("来拆分变量以获取时间,并且还需要删除最后一个字符,即")"符号。
示例:
<script type="text/javascript">
function extractSelectText()
{
var text = document.getElementById("main").options[1].text
/*
var tlength = text.length
var splitno = tlength - 1
var text2 = text.slice(0, splitno)
var textArray = text2.split(" )")
var time = textArray[0]
var hours = textArray[1]
}
</script>
<script type="text/javascript">
function changeSelectText()
{
/* add your code here to determine the value for the time (use variable time) */
/* add your code here to determine the value for the hour (use variable hours) */
var textvalue = time + " (" + hours + ")"
document.getElementById("main").options[1].text
}
</script>
编辑的一个选项是使用一些花哨的模式匹配来更新内容。这将会更慢,需要更多的资源,并且取决于格式的规律性,但不需要进行任何HTML修改。然而,我的担忧在于可访问性和用户体验。值的改变对于屏幕阅读器软件来说很难捕捉到,也可能会使其他用户感到困惑。
这不是一个答案,但或许能帮助到某些人。可以使用details
标签来模拟select
。这个例子并不完整,我使用了JavaScript来在点击时关闭列表。
const items = document.querySelectorAll(".item");
// Add the onclick listeners.
items.forEach(item => {
item.addEventListener("click", e => {
// Close all details on page
closeList(item);
});
});
function closeList(item) {
document.querySelectorAll("details").forEach(deet => {
if (deet != this && deet.open) {
deet.open = !open;
console.log(item);
}
});
}
details {
border: 1px solid #aaa;
border-radius: 4px;
}
summary {
padding: .5em 0 .5em .5em;
font-weight: bold;
}
details[open] {
}
details[open] .item {
cursor: pointer;
padding: .5em 0 .5em .5em;
border-top: 1px solid #aaa;
}
details[open] .item:hover{
background-color: #f1f1f1;
}
details[open] .title{
padding: .5em 0 .5em .5em;
border-top: 1px solid #aaa;
}
<details>
<summary>Select your choice</summary>
<div class='title'>
This is attempt to mimic native <code>select</code> tag with html for <code>option</code> tag
</div>
<div class='item'>item 1</div>
<div class='item'>item 2</div>
<div class='item'>item 3</div>
</details>