Javascript和“div”标签

时间:2014-11-05 14:48:26

标签: javascript html

我想通过JavaScript改变div风格的背景颜色"如果"例行程序,我不明白我收到一条错误消息:"未捕获TypeError:无法设置属性' className' of null"

  <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>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

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

如果你必须使用javascript,则不需要&#39; else&#39; class作为类名.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