当前位置: 代码迷 >> Java Web开发 >> js写的隔行变色成效没有作用
  详细解决方案

js写的隔行变色成效没有作用

热度:2340   发布时间:2013-02-25 21:13:03.0
js写的隔行变色效果没有作用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1.0-transitional.dtd">

<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
  <title>隔行变色</title>
  <style>
  </style>

  <script>
  window.onload = function()
  {
  var oDiv = document.getElementById("div1");
  var oP = oDiv.getElementsByTagName("p");

  var color = "";
  var i=0;
  for(i=1;i<=oP.length;i++)
  {
  if(i%2==0)
  oP.color = "red";
  else
  oP.color = "blue";
  }
  };

  </script>
  </head>

  <body>
  <div id="div1">
  <p>1111111111</p>
  <p>2222222222</p>
  <p>1111111111</p>
  <p>2222222222</p>
  <p>1111111111</p>
  <p>2222222222</p>
  <p>1111111111</p>
  <p>2222222222</p>
  </div>
  </body>
</html>

------解决方案--------------------------------------------------------
首先 把结构搞清楚

JS 这么写 
window.onload = function() {
var oDiv = document.getElementById("div1");
var oP = oDiv.getElementsByTagName("p");

var color = "";
var i = 0;
for (i = 1; i <= oP.length-1; i++) {
if (i % 2 == 0)
{
oP[i].style.backgroundColor="red";
}
else
{
oP[i].style.backgroundColor= "blue";
}
}
};
然后请你用 jqury 很简单
------解决方案--------------------------------------------------------
window.onload = function() {
var oDiv = document.getElementById("div1");
var oP = oDiv.getElementsByTagName("p");

var color = "";
var i = 0;
for (i = 0; i <= oP.length-1; i++) {
if (i % 2 == 0)
{
oP[i].style.backgroundColor="red";
}
else
{
oP[i].style.backgroundColor= "blue";
}
}
};
------解决方案--------------------------------------------------------
for(i=1;i<=oP.length;i++)
{
if(i%2==0)
oP[i].style.color = "red";
else
oP[i].style.color = "blue";
}
就是这个地方的原因
  相关解决方案