我使用下面的jquery函数来突出显示div标签内的一个单词。
{{1}}
};
实际上它只使用一个单词组合但却错过了重复。我使用了mark.js,但我对mark.js有一些其他的限制。谁能告诉我这段代码有什么问题?
答案 0 :(得分:0)
在评论中提及的the answer @SquareCat的启发下,我认为我已经做了一些有用的工作。
顺便说一下,你没有说明你如何称呼这个剧本... 所以我对你使用它的方式可能有误。
但是I reproduced your problem in this CodePen。
然后,I made it working in this CodePen,使用4个正确找到3次的单词。
在下面的片段中,我将我的运气推到了7个单词5次 ;)
jQuery.fn.highlight = function (str, className) {
var target = $(this)[0].innerHTML;
var replacement = "<span class='"+className+"'>"+str+"</span>";
return target.replace(new RegExp(str, 'gi'), replacement );
}
$("#go").on("click",function(){
var words = $("#search").val().split(" ");
var colors = ["yellow","pink","cyan","orange","grey","blue","red"];
for(i=0;i<words.length;i++){
$(document).find("#test").html( $(document).find("#test").highlight(words[i],colors[i]) );
}
});
$("#reset").on("click",function(){
$("#test").find("span").each(function(){
var temp = $(this).html();
$(this).replaceWith(temp);
});
});
&#13;
.yellow{
background-color:yellow;
}
.pink{
background-color:pink;
}
.cyan{
background-color:cyan;
}
.orange{
background-color:orange;
}
.grey{
background-color:grey;
}
.blue{
background-color:blue;
color:white;
}
.red{
background-color:red;
color:white;
}
input{
width:20em;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
This was an interesting problem. Now some part of speach are correctly identified and some part of speach are also correctly identified. Some Other part of speach are identified many times correctly. So to have them correctly identified, some are part of speach is some part of speach are correctly identified. And I know that this sentence is horrible! ;)
</div>
<br>
<input type="text" id="search" value="some part of speach are correctly identified">
<button id="go">GO</button>
<button id="reset">RESET</button>
&#13;