2011-04-01 92 views
1

我正在嘗試製作評分系統,但我與javascript站在一起。我已經做出了一種方法,可以將一顆空白星星的圖像換成一顆星星。我在使用JavaScript設置圖像時遇到了問題

function setStar(intStarId) { 
var stars = new Array("star_one","star_two","star_three","star_four","star_five"); 
for (var i = 0; i < intStarId; i++) 
    document.getElementById(stars[i]).src = "images/star.png"; 
} 

當我稱這種方法時,它不會對星星做任何事情。我怎樣才能使這個工作,因此它交換了明星形象的空白明星形象?

這是我如何在html中調用它。 (它實際上是PHP的,但它呼應HTML)

echo "<script language='javascript'>setStar(3)</script>"; 

這裏是星星的HTML(PHP呼應HTML)

echo "<ul name='a' style='list-style: none; margin: 0px; float: right;'> 
       <li name='b' align='center'> 
        <form name = 'test' action='#' method='post'> 
         <a href='#'><img name='star_one' src='images/star_blank.png' onmouseover='hoverInStar(1)' onmouseout='hoverOutStar(1)'/></a> 
         <a href='#'><img name='star_two' src='images/star_blank.png' onmouseover='hoverInStar(2)' onmouseout='hoverOutStar(2)'/></a> 
         <a href='#'><img name='star_three' src='images/star_blank.png' onmouseover='hoverInStar(3)' onmouseout='hoverOutStar(3)'/></a> 
         <a href='#'><img name='star_four' src='images/star_blank.png' onmouseover='hoverInStar(4)' onmouseout='hoverOutStar(4)'/></a> 
         <a href='#'><img name='star_five' src='images/star_blank.png' onmouseover='hoverInStar(5)' onmouseout='hoverOutStar(5)'/></a> 
        </form> 
       </li> 
      </ul>"; 

回答

2

您試圖通過使用ID找到DOM元素。但是,您的HTML輸出僅包含名稱。嘗試將代碼修改爲低於

echo "<ul name='a' style='list-style: none; margin: 0px; float: right;'> 
       <li name='b' align='center'> 
        <form name = 'test' action='#' method='post'> 
         <a href='#'><img id='star_one' src='images/star_blank.png' onmouseover='hoverInStar(1)' onmouseout='hoverOutStar(1)'/></a> 
         <a href='#'><img id='star_two' src='images/star_blank.png' onmouseover='hoverInStar(2)' onmouseout='hoverOutStar(2)'/></a> 
         <a href='#'><img id='star_three' src='images/star_blank.png' onmouseover='hoverInStar(3)' onmouseout='hoverOutStar(3)'/></a> 
         <a href='#'><img id='star_four' src='images/star_blank.png' onmouseover='hoverInStar(4)' onmouseout='hoverOutStar(4)'/></a> 
         <a href='#'><img id='star_five' src='images/star_blank.png' onmouseover='hoverInStar(5)' onmouseout='hoverOutStar(5)'/></a> 
        </form> 
       </li> 
      </ul>"; 

另請注意,對於DOM中的所有元素,id應該是唯一的。

+0

我什至沒有注意到。謝謝! – Dennis 2011-04-01 14:26:02

1

我認爲你應該使用getElement * sByName *代替getElement * ById * ;-) 要注意,因爲getElementsByName不返回元素,而是一個節點列表:

function setStar(intStarId) { 
    var stars = new Array("star_one","star_two","star_three","star_four","star_five"); 
    for (var i = 0; i < intStarId; i++) { 
     document.getElementsByName(stars[i])[0].src = "images/star.png"; 

    } 
} 
+1

或代替用ID代替名字中你標記由拉梅什也提出了: - ) – 2011-04-01 13:50:48