我正在尝试建立一个评级系统,但我正在使用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 echoing 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>";
答案 0 :(得分: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应该是唯一的。
答案 1 :(得分: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";
}
}
答案 2 :(得分:1)
你应该只使用jQuery,使用下面的库,它会更容易:)
查看http://www.jquery.com/和http://plugins.learningjquery.com/half-star-rating/