简体   繁体   English

用Javascript改变Div的风格

[英]Change Div's Style with Javascript

I'm trying to create a set of divs with content from an array specified on the page in Javascript, then filter the results and change a few of the div's style dependant on the result. 我正在尝试使用Javascript中页面上指定的数组创建一组div,然后根据结果过滤结果并更改一些div的样式。

The current issue with my code is that it seems to only change one div rather than all that currently use the row id. 我的代码当前的问题是它似乎只改变一个div而不是当前使用行id的所有div。

Any help is appreciated, perhaps suggestions as to how I might do parts better. 任何帮助表示赞赏,也许建议我如何做得更好。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript">     </script>
<style type="text/css">
    #testId
    {
        border: 1px solid red;
        width: 300px;
    }
    #row
    {
        border: 1px solid black;
        width: 200px;
    }
    .odd
    {
        border: 1px solid black;
        width: 200px;   
        background-color: #CCC;
    }
    .row2
    {
        color: red;
    }        
</style>
<script type="text/javascript">
var people = [{"name": "Dave" , "age" : 35}, {"name": "Sally" , "age" : 13}, {"name": "Barry" , "age" : 50}, {"name": "Harry" , "age" : 40}, {"name": "Catherine" , "age" : 24}];
function ages()
  {
      var j = 0;
      for (item in people)
      {
          if (people[j]["age"] > 30)
          { 
            var elem = document.getElementById("row");
            elem.style.backgroundColor = "gray";
          }
          j=j+1;          
      }
  }
    $(function () {
        $('#btnRun').bind('click', function (event) {
            $('#testId').html('Here are the results....');          
        });
    });
    </script>
 </head>
 <body>
<div>
    <div id="testId">
    Please click "Run" to show the people:</div>
    <input id="btnRun" type="button" value="Run..." onclick="ages()"/>
    <div id="listContainer">
    <script>
    var c = 0;      
        for (var i=0;i<people.length;i++)
        {

            if (c == 1)
                {
                c = 0;
                document.write("<div id='row'>");
                document.write(people[i]["name"] + " " + people[i]["age"]);
                document.write("</div>");
                }
            else
                {
                c = 1;
                document.write("<div id='row' class='odd'>");
                document.write(people[i]["name"] + " " + people[i]["age"]);
                document.write("</div>");
                }
        }       
    </script>
    </div>
</div>

Research: http://www.w3schools.com/js/default.asp 研究: http//www.w3schools.com/js/default.asp

Change CSS of class in Javascript? 在Javascript中更改类的CSS?

How can I create a two dimensional array in JavaScript? 如何在JavaScript中创建二维数组?

*Edit *编辑

I did it, thanks to everyone who helped! 我做到了,感谢所有帮助过的人! What I ended up doing was changing all the ID's to classes and removed the need to search via getElementById. 我最终做的是将所有ID更改为类,并删除了通过getElementById搜索的需要。

Ill post my code below in the vague hope it might help someone in the future. 我发布下面的代码,模糊地希望它可能在将来帮助某人。

       <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
      <title>test</title>
      <script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
      <style type="text/css">
          #testId
          {
              border: 1px solid red;
              width: 300px;
          }
          .row
          {
              border: 1px solid black;
              width: 200px;
          }
          .odd
          {
              border: 1px solid black;
              width: 200px; 
              background-color: #CCC;
          }
          .red
          {
              border: 1px solid red;
              width: 200px;
              color: red;
          }        
      </style>
      <script type="text/javascript">
      var people = [{"name": "Dave" , "age" : 35}, {"name": "Sally" , "age" : 13}, {"name": "Barry" , "age" : 50}, {"name": "Harry" , "age" : 40}, {"name": "Catherine" , "age" : 24}];
      function ages()
        {

          var html = "";    
              for (var j=0;j<people.length;j++)
              {
                  if (people[j]["age"] > 30)
                  { 
                  var string = people[j]['name'] + ' ' + people[j]['age'];                
                  var html = html + "<div class='red'>" + string + "</div>";
                  }
                  else
                  {
                  var string = people[j]['name'] + ' ' + people[j]['age'];                
                  var html = html + "<div class='row'>" + string + "</div>";    
                  }
              }
              document.getElementById("listContainer").innerHTML=html;  




        }
          $(function () {
              $('#btnRun').bind('click', function (event) {
                  $('#testId').html('Here are the results....');            
              });
          });
      </script>
  </head>
  <body>
      <div>
          <div id="testId">
          Please click "Run" to show the people:</div>
          <input id="btnRun" type="button" value="Run..." onclick="ages()"/>
          <div id="listContainer">
          <script>
          var c = 0;
          var html = "";    
              for (var i=0;i<people.length;i++)
              {

                  var string = people[i]['name'] + ' ' + people[i]['age'];

                  if (c == 1)
                      {
                      c = 0;
                      var html = html + "<div class='row'>" + string + "</div>";

                      }
                  else
                      {
                      c = 1;
                      var html = html + "<div class='row, odd'>" + string + "</div>";
                      }
              }
              document.getElementById("listContainer").innerHTML=html;  
          </script>
          </div>
      </div>
  </body>
  </html>

The Id attribute should have a unique value for each element it is defined on. Id属性应为其定义的每个元素具有唯一值。 Using document.getElementById only returns a single element, the first that is finds with the matching id. 使用document.getElementById只返回一个元素,第一个使用匹配的id查找。 Hence Element and not Elements. 因此元素而不是元素。

In this case you should use a class as a flag or use the name attribute to find the matching elements. 在这种情况下,您应该使用类作为标志或使用name属性来查找匹配的元素。

As everyone else has stated you need to use classes instead of Ids because ids must be unique. 正如其他人所说,你需要使用类而不是ID,因为id必须是唯一的。 Then you can set the background-color of elements with a certain class ( row in this example) like this: 然后你可以设置元素的background-color与某个类(在这个例子中的row ),如下所示:

$(".row").css("background-color", "grey");

This uses jQuery which you have included. 这使用了你包含的jQuery。

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

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