开发者

How to change style of multiple elements?

开发者 https://www.devze.com 2023-01-26 12:25 出处:网络
I have a let\'s say ten thumb-pics of horses. And each time one horse gets clicked I would like its background to become grey. And the same when another horse gets clicked I would like that horse\'s b

I have a let's say ten thumb-pics of horses. And each time one horse gets clicked I would like its background to become grey. And the same when another horse gets clicked I would like that horse's background color to become grey and with it, all the other backgrounds to become back white.

If I do it like this

function changeBackHorse(id) {
  for (var i = 0; i < 25; i++) {
   if (id == i) { 
     document.getElementById("horseThumb_" + id)
       .style.backgroundColor = '#888';
   }
  }
}

The background of the clicked horse changes. All I have to do now is to add an else statement so that when the ID isn't the same the backgrounds become white.开发者_如何学运维

So I thought I thought this would work and have no idea why it doesn't. Nothing happens, though the ID passed is correct. (tested with alert(id)).

<span id="horseThumb_<%= horse_thumb.id %>"
 onclick="changeBackHorse('<%= horse_thumb.id %>');">
 <%= image ... %>
</span>    

script:

function changeBackHorse(id) {
  for (var i = 0; i < 25 ; i++) {
   var el = document.getElementById("horseThumb_" + i);
   if (id == i){
    el.style.backgroundColor = '#888';
   } else {
    el.style.backgroundColor = '#fff';
   }
  }
}​

I don't know what I am doing wrong here. I tried changing it in various ways but can't figure out why it doesn't work. So any answers would be very appreciated!


Confirm is that script running without throwing any error? I suspect the following statement:

for (i;i<25;i++) { ...

Make sure the count is correct. I've trim your code and it works for me:

<html>
<head>
<script>
function changeBackHorse(id){
  var i=0;
  for (i;i<5;i++) {
   if (id == i){
    document.getElementById("horseThumb_"+id).style.backgroundColor='#888'
   }
   else{
    document.getElementById("horseThumb_"+i).style.backgroundColor='#fff'

   }
  }
}
window.onload = function() {
 changeBackHorse(1);
}
</script>
</head>
<body>
<div id="horseThumb_0">horse 0</div>
<div id="horseThumb_1">horse 1</div>
<div id="horseThumb_2">horse 2</div>
<div id="horseThumb_3">horse 3</div>
<div id="horseThumb_4">horse 4</div>
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消