2011-04-01 58 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