search.length是否有办法从段落中检索文本并更改其颜色?
我尝试了:<p id="userInput">1,2,3,4,5,6,7,some text,another text</p>
var qq = document.getElementById("userInput").innerHTML.match(/5/g);
var blaaa = qq.style.color = "red";
document.getElementById("userInput").innerHTML = blaaa;
编辑:
var search = ['new', 'and'];
$(document).ready(function () {
for(var i = 0;i<2;i++){
$("div:contains('"+search[i]+"')").each(function () {
var regex = new RegExp(search[i],'gi');
$(this).html($(this).text().replace(regex, "<span class='red'>"+search[i]+"</span>"));
});
}
});
答案 0 :(得分:2)
否则没有,除非你将文本包装在它自己的元素中,例如span
var el = document.getElementById("userInput");
el.innerHTML = el.innerHTML.replace(/(5)/g, '<span style="color: red">$1</span>');
<p id="userInput">1,2,3,4,5,6,7,some text,another text</p>