Javascript 我可以在选择元素的选项中使用 HTML 标签吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11237807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:04:19  来源:igfitidea点击:

Can I use HTML tags in the options for select elements?

javascriptjqueryhtmlcss

提问by trubliphone

Is it possible for the options of an HTML select element to include HTML tags?

HTML 选择元素的选项是否可以包含 HTML 标签?

For example, given the following code:

例如,给定以下代码:

 <select>
    <option value="one"><b>one is bold</b></option>
    <option value="two">two has some <span style='color:red;'>red</span> text</option>
    <option value="three">three is just normal</option>
 </select>

I would like the options to actually render in HTML. In this application I can play with HTML, CSS, JavaScript (including jQuery). And the HTML itself is being rendered via Django (django.form.fields.select).

我想要在 HTML 中实际呈现的选项。在这个应用程序中,我可以使用 HTML、CSS、JavaScript(包括 jQuery)。并且 HTML 本身是通过 Django (django.form.fields.select) 呈现的。

回答by meagar

No, you can't do this. <option>tags cannot contain any other tags.

不,你不能这样做。<option>标签不能包含任何其他标签。

回答by nunespascal

No, you cannot.

你不能。

What you would do if you wanted this is use something like a floating div and position and display it using Css to look like a select. Then using javascipt clicks allow users to select.

如果你想要这个,你会做的是使用类似浮动 div 和位置的东西,并使用 Css 显示它看起来像一个选择。然后使用javascipt点击让用户选择。

Something like this: Reinventing the dropdown

像这样:重新发明下拉菜单

回答by Michael Durrant

No, but this: Styling HTML Selectmay help you and there a lof of detail and votes here:

不,但是这个:样式化 HTML 选择可以帮助你,这里有很多细节和投票:

How to style a <select> dropdown with CSS only without JavaScript?

如何在没有 JavaScript 的情况下仅使用 CSS 设置 <select> 下拉列表的样式?

回答by charlietfl

option tag does not allow any children other than text

选项标签不允许除文本之外的任何子项

Here is a fiddle I created a few months ago that replaces a select element with a list dropdown, and updates the select for each selection made. Just hide select with css http://jsfiddle.net/6zcRk/

这是我几个月前创建的一个小提琴,它用一个列表下拉列表替换了一个选择元素,并为每个选择更新了选择。只需使用 css http://jsfiddle.net/6zcRk/隐藏选择

The user in this thread then turned it into a plugin available on github( see link in thread)

此线程中的用户然后将其转换为 github 上可用的插件(请参阅线程中的链接)

Custom drop-down panel with jQuery

使用 jQuery 自定义下拉面板