我有一个包含三列的表,如下所示:
类别 |项目|STATUS
该表填充了来自 php 脚本的数据
我需要确保如果“PRIORITY”值是 php 数据导入的结果,标题“STATUS”下的单元格将更改为红色背景和白色文本颜色。
这是我的js脚本
<script>
function c_color(){
if (document.getElementById('CellColor').value = 'PRIORITY') {
document.getElementById('CellColor').style.color = "white";
document.getElementById('CellColor').style.background="red";
}
}
c_color();
</script>
这是调用该函数的 HTML/PHP
<td id="CellColor" style="background-color: #92c38e; text-align:
center;">
<span style="color: #ffffff; font-size: medium;">
<?php print strip_tags($category[0]['status']); ?></span></td>
结果我只得到第一个带有红色和白色的单元格,但这甚至没有显示“优先级”值
我已经尝试了一遍又一遍,但我无法做到正确,任何帮助将不胜感激。
Use ==
or ===
for JavaScript 中的比较.
你的代码:
if (document.getElementById('CellColor').value = 'PRIORITY')
分配一个值,因为它使用单个等号(这总是会导致if
进入true
分支)。
另外,还有一个 HTMLtd
元素不会有value
属性(仅表单元素具有)。使用以下命令访问非表单元素的文本内容textContent财产。
此外,请确保您的 JavaScript 代码放置在紧挨着结束之前<body>
元素或者您将其包含在回调中window
's DOMContentLoaded
事件以确保它不会在需要使用的 HTML 元素被解析之前运行。
现在,除了这些要点之外,这只是一个友好的“最佳实践”建议。尝试摆脱硬编码或在 HTML 元素上动态创建“内联样式”。该技术很快就会变得混乱,并且可能会产生可伸缩性问题,因为内联样式在需要时很难覆盖。相反,提前编写 CSS 类,然后根据需要简单地添加或删除这些类。
这是一个例子:
// The following code won't run until all the HTML has been parsed into memory
window.addEventListener("DOMContentLoaded", function(){
// Just scan the DOM for the element one time
var theCell = document.getElementById('CellColor');
// Here, we're just testing to see if the cell "contains" the text "PRIORITY",
// not that it exactly equals it.
if (theCell.textContent.indexOf('PRIORITY') > -1) {
// Just add the pre-made class and you're done
theCell.classList.add("special");
}
});
td {
background-color: #92c38e;
text-align: center;
}
.span {
color: #ffffff;
font-size: medium;
}
.special {
color:white;
background-color:red;
}
<table>
<tr>
<td id="CellColor">PRIORITY
<span class="span">span sample</span>
</td>
</tr>
</table>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)