我想在javascript中編寫一個星級評分系統,它允許用戶重新評估(是一個單詞嗎?)。我很新的Javascript和節目一般,但這裏是我到目前爲止有:按價值複製Javascript DOM對象
<div id="rateMe" title="Rate Me...">
<a><img id="star1" onMouseOver="mOverRate(this);" onMouseOut="mOutRate(this);"
onMouseDown="mClickRate(this);" src="star_empty.png"/></a>
<a ><img id="star2" onMouseOver="mOverRate(this);" onMouseOut="mOutRate(this);"
onMouseDown="mClickRate(this);" src="star_empty.png"/></a>
<a><img id="star3" onMouseOver="mOverRate(this);" onMouseOut="mOutRate(this);"
onMouseDown="mClickRate(this);" src="star_empty.png"/></a>
<a><img id="star4" onMouseOver="mOverRate(this);" onMouseOut="mOutRate(this);"
onMouseDown="mClickRate(this);" src="star_empty.png"/></a>
<a><img id="star5" onMouseOver="mOverRate(this);" onMouseOut="mOutRate(this);"
onMouseDown="mClickRate(this);" src="star_empty.png"/></a>
<label id="info0"></label>
<label id="info1"></label>
<label id="info2"></label>
<label id="info3"></label>
<label id="info4"></label>
</div>
<script type="text/javascript">
var Rated = false;
// Declare an array that holds refers to the star img objects
var aryImg = new Array(document.getElementById("star1"), document.getElementById("star2"),
document.getElementById("star3"), document.getElementById("star4"),
document.getElementById("star5"));
// Decare an array that will be used to store the star rating
// when a user clicks and chooses a rating
aryStoredImg = aryImg;
function mOverRate(that)
{
var myImg = that;
// Changes the star image to filled (and any images to the right
// of it) if the mouse is hovering over it
switch (myImg.id)
{
case "star1":
aryImg[0].src = "star_filled.png";
break;
case "star2":
for (var i = 0; i <= 1; i++)
{
aryImg[i].src = "star_filled.png";
}
break;
case "star3":
for (var i = 0; i <= 2; i++)
{
aryImg[i].src = "star_filled.png";
}
break;
case "star4":
for (var i = 0; i <= 3; i++)
{
aryImg[i].src = "star_filled.png";
}
break;
case "star5":
for (var i = 0; i <= 4; i++)
{
aryImg[i].src = "star_filled.png";
}
break;
}
}
function mClickRate(that)
{
// This attempts to store the state of the imgs
// after the user clicks a star
for (var i = 0; i < aryImg.length; i++)
{
aryStoredImg[i].src = aryImg[i].src;
}
Rated = true;
}
function mOutRate(that)
{
var myImg = that;
if (Rated)
{
// This replaces the images displayed with the
// images that were stored at the time the user
// clicked on a star
for (var i = 0; i < aryImg.length; i++)
{
aryImg[i].src = aryStoredImg[i].src;
}
}
else
{
// This resets all of the images after the mouse
// out event
for (var i = 0; i < aryImg.length; i++)
{
aryImg[i].src = "star_empty.png";
}
}
}
在mClickRate()函數,我想存儲當前源,以便我可以在mOutRate()函數中調用它,以在用戶不再次點擊時恢復用戶的選擇。然而,經過一些研究(好的很多研究)後,我發現我的新陣列指向相同的參考。
我已經嘗試使用array.splice,我也試過使用沒有任何運氣的循環。如果任何人有任何幫助提供按價值複製這種類型的數組,而不是參考或建議如何使我的腳本更好,請讓我知道。
哦,我是否說過我是初學者(回答時請記住這一點)?提前致謝。
我花了兩天研究如何解決這個問題。談論太多思考。你的回答非常簡單明瞭。謝謝 – yerty
幾乎所有的程序設計都值得您考慮如何讓您的數據(評估值)與用戶界面(星星的顯示細節)分離開來,以便隨時更改界面,而不是必須改變你存儲的數據。這種思維會在這種情況下幫助你。 – jfriend00
我會記住這一點。再次感謝 – yerty