2014-11-05 89 views
-5

我想通过JavaScript“if”例程更改div样式的背景颜色,无法得到错误消息:“Uncaught TypeError:无法设置属性'className'为null”Javascript和“div”标签

<head> 
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script> 
     <style type="text/css"> 
      .ok{ background-color:green; } 
      .dead{ background-color:red; } 
     </style> 

<script type="text/javascript"> 


function emea(){ 


    if (<?php echo $variable;?>==1) { 


     document.getElementById('test').className = 'ok'; 
    } 
    else { 

     document.getElementById('test').className = 'dead'; 
    } 
} 

emea(); 
    </script> 

</head> 

<div id="test">BlaBla</div> 
+5

_javascript_,不_JAVA script_。它与java无关。 – BackSlash 2014-11-05 14:49:25

+0

*我想通过javascript“if”例程更改div样式的背景颜色:*确定。有什么问题? – Compass 2014-11-05 14:51:39

+1

为什么打开PHP标签? – 2014-11-05 14:51:46

回答

1

看起来你接近,你只需要花费一点时间检查您的格式...

有很多在这里没有答案的问题,但是这是你在拍摄,我觉得。

<head> 

<style type="text/css"> 
.ok 
{ 
    background-color:green; 
} 

.dead 
{ 
    background-color:red; 
} 
</style> 

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script> 
<script type="text/javascript"> 

var variable1 = '<?php echo($variable1); ?>'; 

function emea() 
{ 
    if(variable1 !== '') 
    { 
     document.getElementById('test').className = 'dead'; 
    } 
    else 
    { 
     document.getElementById('test').className = 'ok'; 
    } 
} 
</script> 

</head> 

<body onload="emea();"> 

<div id="test">BlaBla</div> 

</body> 
0

我不得不问,为什么不用PHP来改变div的类呢?

<div id="test" class="<?php echo ($variable == 1) ? 'ok' : 'dead'; ?>"></div> 

如果必须使用JavaScript则是作为类名.dead的“其他”条款没有真正的需要是默认的类:

var phpVar = <?php echo $variable; ?>; 

if (phpvar == 1) 
    document.getElementById('test').className = 'ok'; 

然后,只需设置默认类的html:

另外,我注意到你的jQuery包含在你的例子中,并且你的问题还没有足够的说明你是否真的使用它。如果你是,那么你可以使用:

$('#test').prop('class', 'ok') 

我会坚持使用纯JS版但是是快近4倍:http://jsperf.com/jquery-addclass-vs-attr-class-vs-prop-class

+0

PHP只是一个例子。代码位于PLC的Web服务器上,在那里我可以使用像<%ReadPLC(“Variable”);%>这样的ASP标签,因此请使用Javascript。我不能使用任何“如果,那么,其他,而......”。 – knuppel 2014-11-05 15:50:42