简体   繁体   English

如何使用Javascript和Ajax更改div背景颜色?

[英]How to change div background color using Javascript and Ajax?

I am trying to change background color of div using Ajax and Javascript, but my code is not working: 我正在尝试使用Ajax和Javascript更改div背景颜色,但是我的代码无法正常工作:

Code: 码:

<script type="text/javascript">
    window.rowcount=function() {
        var exam = new XMLHttpRequest();
        exam.onreadystatechange = function() {
            if (exam.readyState == 4) {                             
                var i=document.getElementById("newdata").innerHTML = exam.responseText;
                if(i==1){
                    document.getElementsById("newdata").style.backgroundColor = green;                  
                }

            }
        }
        exam.open("GET", "demo1.php?", true);
        exam.send(null);

</script>

Where am I wrong in this code? 我在此代码中哪里写错了?

Any help will be appreciated. 任何帮助将不胜感激。

The problem is that green is not defined. 问题是未定义green You can use "green" or #00FF00 . 您可以使用"green"#00FF00

Try this: 尝试这个:

    <script type="text/javascript">
    window.rowcount=function() {
        var exam = new XMLHttpRequest();
        exam.onreadystatechange = function() {
            if (exam.readyState == 4) {


                var i=document.getElementById("newdata").innerHTML = exam.responseText;
             if(i==1){
                  document.getElementsById("newdata").style.backgroundColor = "#00FF00";

             }

            }
        }
        exam.open("GET", "demo1.php?", true);
        exam.send(null);

    </script>

You forgot a bracet and green needs to be a string, so: 您忘记了bracet,绿色必须是字符串,因此:

<script type="text/javascript">
  window.rowcount=function(){
    var exam=new XMLHttpRequest();
    exam.onreadystatechange=function(){
      if(exam.readyState==4){
        var i=document.getElementById("newdata").innerHTML=exam.responseText;
      }
      if(i==1){
        document.getElementsById("newdata").style.backgroundColor="green";
      }
    }
  }
  exam.open("GET", "demo1.php?", true);
  exam.send();
</script>

By Typing green You Pass in a variable. 通过键入绿色,您可以传入变量。 Type "Green" instead 键入“绿色”代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM