经过几次尝试和大量搜索,我还没有找到解决这个问题的方法(尽管我对Java语言不是很熟悉!)。 我有一个表(将动态创建),在其中希望用图标替换关键字。这些关键字只会是'Green'或'Yellow',但是作为字符串一部分的日期是动态的,需要保留(我将在后面整理其格式)。
我的HTML:
<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
<tr><th>Name</th><th>SOP ABC</th></tr>
<tr><td>Mary Coppen</td><td>Green10/5/18</td></tr>
<tr><td>Arlana Mycroft</td><td>Green12/6/18</td></tr>
<tr><td>Bob Litchfield</td><td>Yellow05/09/18</td></tr>
</table>
我的JavaScript:
var tds = document.getElementsByTagName('td');
var Gimg = "<img src='/Content/StatusOK_16x.gif' />";
var Yimg = "<img src='/Content/StatusWarning_12x_16x.gif' />";
for (var i = 0; tds[i]; i++) {
if (tds[i].innerHTML.includes('Green')) {
tds[i].innerHTML.replace('Green', Gimg)
}
if (tds[i].innerHTML.includes('Yellow')) {
tds[i].innerHTML.replace('Yellow', Yimg)
}
}
非常感谢您的任何建议!
答案 0 :(得分:1)
.replace
返回一个字符串,您需要将其分配给目标innerHTML
尝试以下代码:
var tds = document.getElementsByTagName('td');
var Gimg = "<img src='/Content/StatusOK_16x.gif' />";
var Yimg = "<img src='/Content/StatusWarning_12x_16x.gif' />";
for (var i = 0; i < tds.length; i++) {
if (tds[i].innerHTML.includes('Green')) {
tds[i].innerHTML = tds[i].innerHTML.replace('Green', Gimg)
}
if (tds[i].innerHTML.includes('Yellow')) {
tds[i].innerHTML = tds[i].innerHTML.replace('Yellow', Yimg)
}
}
编辑:-i
答案 1 :(得分:1)
var tds = document.getElementsByTagName('td');
var Gimg = "<img src='/Content/StatusOK_16x.gif' />";
var Yimg = "<img src='/Content/StatusWarning_12x_16x.gif' />";
for (var i = 0; i<tds.length; i++) {
if (tds[i].innerHTML.includes('Green')) {
tds[i].innerHTML =tds[i].innerHTML.replace(/Green/gi, Gimg)
}
if (tds[i].innerHTML.includes('Yellow')) {
tds[i].innerHTML = tds[i].innerHTML.replace(/Yellow/gi, Yimg)
}
}
@ elegant-users用户回答的是正确的。
我只想对此添加一些解释。
为什么您的代码无法正常工作?
答案 2 :(得分:-1)
这里是solution
var tds = document.getElementsByTagName('td');
var Gimg = "<img src='https://via.placeholder.com/150' />";
var Yimg = "<img src='https://via.placeholder.com/150'/>";
for(var i=0; i < tds.length; i++) {
const name = tds[i].innerHTML;
if (name.includes('Green')) {
tds[i].innerHTML = Gimg;
}
if (name.includes('Yello')) {
tds[i].innerHTML = Yimg;
}
}