我试图替换一个短语中一个单词的颜色,但是它把跨度当作文本而不是元素,我想这是因为我正在创建一个文本节点,我如何使它工作呢?
function wordQuery() {
let data = document.getElementById("queryWordInput").value
let list = document.getElementById("queryWordResults");
list.innerHTML = ""
for (let purchase of Sys.listOfPurchases) {
let node = document.createElement('li');
let text = purchase.description.replace(data, "<span style='color:red'>" + data + "</span>");
let text1 = document.createTextNode(text);
node.appendChild(text1);
list.appendChild(node);
}
}
您希望使用innerHTML,因为这样它还会将data
转换为实际元素。
function wordQuery() {
let data = document.getElementById("queryWordInput").value
let list = document.getElementById("queryWordResults");
list.innerHTML = ""
for (let purchase of Sys.listOfPurchases) {
let node = document.createElement('li');
let text = purchase.description.replace(data, "<span style='color:red'>" + data + "</span>");
node.innerHTML = text;
list.appendChild(node);
}
}