为< select> s的所选选项显示不同的文本 [英] Show a different text for the selected option for `<select>`s
问题描述
我希望< select>
中显示的文本与选定的< option>
的文字。我的宽度有限,因此,如果我在< option>
中显示所有文本,则某些文本会被剪掉。
例如,如果我的标记是这样:
< select>
< option>打开(一些说明)< / option>
< option>已关闭(一堆文本< / option>
< / select>
当选择第一个选项时,我只想显示单词 Open以节省空间。我不能只使用Javascript来替换文本,因为如果用户打开了select,那么他们会
有没有一种方法可以使用< select>
标签(即不使用使用自定义选择器)?
使用JS,您可以添加焦点
和 blur
事件监听器,它们修改选项
s的文本:
function focus(){[] .forEach.call(this.options,function(o){o.textContent = o.getAttribute('value')+'('+ o.getAttribute('data-descr')+')';});} function blur(){[] .forEach.call(this.options,functi on(o){console.log(o); o.textContent = o.getAttribute('value'); });} []。forEach.call(document.querySelectorAll('。shortened-select'),函数(s.addEventListener('focus',focus); s.addEventListener('blur',blur);
<选择class = shortened-select> < option value =打开 data-descr =一些描述>< / option> < option value =已关闭 data-descr =一堆文本>< / option>< / select>
I want the text that's displayed in the <select>
to be different from the selected <option>
's text. I have limited width to work with, so if I display all the text in the <option>
, then some text with be cut off.
For example, if my markup is this:
<select>
<option>Open (some description)</option>
<option>Closed (a bunch of text</option>
</select>
When the first option is selected, I want to show only the word "Open" to save space. I can't just use Javascript to replace the text because if the user opens the select, then they'll see the shortened text.
Is there a way to do this using the <select>
tag (i.e. without using a custom selector)?
Using JS, you can add a focus
and blur
event listeners which modify the text of the option
s:
function focus() {
[].forEach.call(this.options, function(o) {
o.textContent = o.getAttribute('value') + ' (' + o.getAttribute('data-descr') + ')';
});
}
function blur() {
[].forEach.call(this.options, function(o) {
console.log(o);
o.textContent = o.getAttribute('value');
});
}
[].forEach.call(document.querySelectorAll('.shortened-select'), function(s) {
s.addEventListener('focus', focus);
s.addEventListener('blur', blur);
blur.call(s);
});
<select class="shortened-select">
<option value="Open" data-descr="some description"></option>
<option value="Closed" data-descr="a bunch of text"></option>
</select>
这篇关于为< select> s的所选选项显示不同的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!