[英]How to change div background color using Javascript and Ajax?
我正在尝试使用Ajax和Javascript更改div
背景颜色,但是我的代码无法正常工作:
码:
<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>
我在此代码中哪里写错了?
任何帮助将不胜感激。
问题是未定义green
。 您可以使用"green"
或#00FF00
。
尝试这个:
<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>
您忘记了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>
通过键入绿色,您可以传入变量。 键入“绿色”代替
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.