如果内容不同,此JavaScript代码将更改div的背景:
function myfunction() {
$a = document.getElementById('t').getElementsByTagName('div');
var x = 0;
while(x < $a.length) {
var b = ($a[x].innerHTML);
b.toString;
alert(x + b[x]);
if(b == 'PENDING SELECTING TEAM MEMBER' ||b == 'PENDING APPROVAL BY SCHEME MANAGER' ||b == 'PENDING SELECTING TEAM MEMBER' ||b == 'PENDING REVIEW TEAM MEMBER BY LEAD ASSESSOR' ||b == 'PENDING ACKNOWLEDGEMENT BY TA/LA' ||b == 'PENDING PREPARE AUDIT PLAN BY LA' ||b == 'PENDING REVIEW AUDIT PLAN BY AO' ||b == 'PENDING ACCEPT LA BY LAB' ||b == 'PENDING VERIFY REASON BY AO' ||b == 'PENDING CONDUCT ASSESSMENT' || b == 'PENDING CORRECTIVE ACTION BY CAB' || b == 'PENDING REVIEW BY AO' || b == 'PENDING CORRECTIVE ACTION APPROVAL BY SCHEME MANAGER' ||b == 'PENDING APPROVAL BY DOA' ){
document.getElementById('status'+x).style.background="maroon";
alert(x + b);
}
x++;
}
}
它不起作用,因为if
语句失败。
有人可以帮我弄清楚出了什么问题吗?
答案 0 :(得分:2)
作为备注,b.toString;
应为b.toString();
我个人更喜欢使用双引号,但这只是因为习惯强烈地输入它们并且字符和字符串之间存在差异。
看到其他人说出来,但只是强调:没有'var'关键字的函数中的变量使它们成为全局变量,这意味着它们是可访问的,并且可以在程序的任何范围内更改。 /强> 的
尝试使用以下javascript代码:JSFiddle
更改了设置背景颜色的方式。
答案 1 :(得分:0)
考虑使用underscore.js
中的_.contains
,这会使if
稍微复杂一点。相反,它看起来更像是:
var collection = [
'PENDING SELECTING TEAM MEMBER',
'PENDING APPROVAL BY SCHEME MANAGER',
'PENDING SELECTING TEAM MEMBER',
'PENDING REVIEW TEAM MEMBER BY LEAD ASSESSOR',
'PENDING ACKNOWLEDGEMENT BY TA/LA',
'PENDING PREPARE AUDIT PLAN BY LA',
'PENDING REVIEW AUDIT PLAN BY AO',
'PENDING ACCEPT LA BY LAB',
'PENDING VERIFY REASON BY AO',
'PENDING CONDUCT ASSESSMENT',
'PENDING CORRECTIVE ACTION BY CAB',
'PENDING REVIEW BY AO',
'PENDING CORRECTIVE ACTION APPROVAL BY SCHEME MANAGER',
'PENDING APPROVAL BY DOA'];
if(_.contains(collection, b)) {
alert("this condition is true!");
//...
}
如果它发出警报,那么if语句中就会出现问题。如果没有,则不满足条件,我可能首先查看HTML中的前导和尾随空格。
答案 2 :(得分:0)
您可以通过简化来“测试”您的if语句(这是一种通用的调试技术):
var b = 'PENDING SELECTING TEAM MEMBER';
if (b == 'PENDING SELECTING TEAM MEMBER' || b == 'PENDING APPROVAL BY SCHEME MANAGER' || b == 'PENDING SELECTING TEAM MEMBER' || b == 'PENDING REVIEW TEAM MEMBER BY LEAD ASSESSOR' || b == 'PENDING ACKNOWLEDGEMENT BY TA/LA' || b == 'PENDING PREPARE AUDIT PLAN BY LA' || b == 'PENDING REVIEW AUDIT PLAN BY AO' || b == 'PENDING ACCEPT LA BY LAB' || b == 'PENDING VERIFY REASON BY AO' || b == 'PENDING CONDUCT ASSESSMENT' || b == 'PENDING CORRECTIVE ACTION BY CAB' || b == 'PENDING REVIEW BY AO' || b == 'PENDING CORRECTIVE ACTION APPROVAL BY SCHEME MANAGER' || b == 'PENDING APPROVAL BY DOA')
{
alert("Working");
}