2014-11-05 144 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