Javascript 如何使用Jquery代码在select option html元素中高亮显示单词
有人能帮我解决这个问题吗:我想用jquery突出显示selectoptionhtml元素中的一个单词。例如:Javascript 如何使用Jquery代码在select option html元素中高亮显示单词,javascript,jquery,html,Javascript,Jquery,Html,有人能帮我解决这个问题吗:我想用jquery突出显示selectoptionhtml元素中的一个单词。例如: <select> <option value="volvo">Volvo</option> <option value="saab">not Saab</option> <option value="vw">VW</option> <option value="audi">b
<select>
<option value="volvo">Volvo</option>
<option value="saab">not Saab</option>
<option value="vw">VW</option>
<option value="audi">but Audi</option>
</select>
沃尔沃汽车
不是萨博
大众汽车
但是奥迪
单词“not”应该是红色,单词“but”应该是绿色(带有CSS)。我发现下面的代码有一个类似的问题,但是我可以修改jquery代码,使其与optionselect元素一起工作。有人给我们提供这个问题的解决方案吗?谢谢这是不可能的,因为您需要一个附加元素来包装单词“not”,但是
选项
元素只能包含文本内容
至少在Chrome和Firefox中,您甚至不能在选项中包含伪元素
[value=saab]::在{content:“not”}之前
沃尔沃汽车
萨博
大众汽车
但是奥迪
可以使用jQueryUI selectmenu来完成,它取代了本机select元素:
HTML:
沃尔沃汽车
不是萨博
大众汽车
但是奥迪
jQuery:
$( function() {
$.ui.selectmenu.prototype._renderItem = function (ul, item) {
var text = String(item.label);
if (text.match(/not/)) {
text = text.replace(
new RegExp('not', 'gi'),
'<strong style="color:red;">$&</strong>');
}
if (text.match(/but/)) {
text = text.replace(
new RegExp('but', 'gi'),
'<strong style="color:green;">$&</strong>');
}
return $("<li></li>")
.data("item.selectmenu", item)
.append("<div>" + text + "</div>")
.appendTo(ul);
};
$( "#myselect" ).selectmenu({
width: 150
});
});
$(函数(){
$.ui.selectmenu.prototype.\u renderItem=函数(ul,项){
var text=字符串(item.label);
if(text.match(/not/)){
text=text.replace(
新的RegExp('not','gi'),
“$&”;
}
if(text.match(/but/)){
text=text.replace(
新的RegExp('but','gi'),
“$&”;
}
返回$(“”)
.data(“项.选择菜单”,项)
.append(“+text+”)
.附录(ul);
};
$(“#我的选择”)。选择功能表({
宽度:150
});
});
演示:它可以工作:。您必须包含jQuery库、jQueryUI库和jQueryUI CSS才能工作(如我的代码笔演示的HTML所示)。
$( function() {
$.ui.selectmenu.prototype._renderItem = function (ul, item) {
var text = String(item.label);
if (text.match(/not/)) {
text = text.replace(
new RegExp('not', 'gi'),
'<strong style="color:red;">$&</strong>');
}
if (text.match(/but/)) {
text = text.replace(
new RegExp('but', 'gi'),
'<strong style="color:green;">$&</strong>');
}
return $("<li></li>")
.data("item.selectmenu", item)
.append("<div>" + text + "</div>")
.appendTo(ul);
};
$( "#myselect" ).selectmenu({
width: 150
});
});