简体   繁体   中英

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.

The current issue with my code is that it seems to only change one div rather than all that currently use the row id.

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

Change CSS of class in Javascript?

How can I create a two dimensional array in 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.

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. Using document.getElementById only returns a single element, the first that is finds with the matching 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.

As everyone else has stated you need to use classes instead of Ids because ids must be unique. Then you can set the background-color of elements with a certain class ( row in this example) like this:

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

This uses jQuery which you have included.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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