我有一个突出显示jquery插件的单词,可以检测div中的一个单词(在本例中为pre),然后突出显示它。我编辑它所以它可以检测多个单词,但它只能检测每个函数一个单词,我希望它能够找到每个函数的多个单词(排序类似于语法荧光笔)。
的 HTML:
<!Doctype HTML>
<html>
<head>
<link rel="stylesheet" href="i.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="css.js" type="text/javascript"></script>
</head>
<body onload="page();">
<button ontouchstart="page()">execute</button>
<script>
function page() {
get();
spud();
spuds();
getting();
}
function getting() {
var rego = 'get';
$('pre').highlight(rego,'green');
}
function get() {
var regi = 'hget';
$('pre').highlight(regi,'green');
}
function spud() {
var you = 'potato';
$('pre').highlight(you,'highlight'); // change 'you' with a var value
}
function spuds() {
var your = 'chips';
$('pre').highlight(you,'highlight'); // change 'you' with a var value
}
</script>
<pre contenteditable="true" id="pre">
get potato chips
hget potato chips now
</pre>
</body>
</html>
CSS:
.highlight { color: red }
.green { color:green}
插件:
jQuery.fn.highlight = function(e,spill) {
function t(e, i) {
var h = 0;
if (3 == e.nodeType) {
var n = e.data.toUpperCase().indexOf(i);
if (n -= e.data.substr(0, n).toUpperCase().length - e.data.substr(0, n).length,
n >= 0) {
var a = document.createElement("pig");
a.className = spill;
var r = e.splitText(n);
r.splitText(i.length);
var s = r.cloneNode(!0);
a.appendChild(s), r.parentNode.replaceChild(a, r), h = 1;
}
} else if (1 == e.nodeType && e.childNodes && !/(script|style)/i.test(e.tagName)) for (var l = 0; l < e.childNodes.length; ++l) l += t(e.childNodes[l], i);
return h;
}
return this.length && e && e.length ? this.each(function() {
t(this, e.toUpperCase());
}) :this;
}, jQuery.fn.removeHighlight = function() {
return this.find("pig."+spill+"").each(function() {
with (this.parentNode.firstChild.nodeName, this.parentNode) replaceChild(this.firstChild, this),
normalize();
}).end();
};
我的目标是在变量rego regi you your
中有多个值
。例如,在var your
中我想要类似:var your = "chips","kumara","grease";
,我已经尝试var your = ["chips","kumara","grease"];
,但它已经无效了。
答案 0 :(得分:1)
可以尝试替换:
return this.length && e && e.length ? this.each(function() {
t(this, e.toUpperCase());
}) :this;
使用
return this.length && e && e.length ? this.each(function() {
var arr = typeof e === 'string' ? [e] : e,
self=this;
$.each(arr, function(_, term){
if(term.length){
t(self, term.toUpperCase());
}
});
}) :this;
现在正在检查值是字符串还是数组,因此您可以使用