我正在研究一個我在高中稱爲「毒品戰爭」的舊遊戲的複製品。我有全球變量,持有所擁有的每種藥物的數量。最初,我對每種藥物的每次買賣都使用了不同的功能。爲了節省自己的一些代碼並提供一定的擴展能力,我希望將其改爲一種購買功能,通過藥品,藥品(通過不同的功能完成)和藥品名稱。在不使用變量名的情況下更新Javascript函數中的全局變量
我堅持的部分是試圖將drugqty(在函數中本地使用)更新爲全局變量。
function buy(drugqty, drugprice, drugname)
{
if (money < drugprice)
{
window.alert("You do not have enough money to do that!")
}
else if(money >= drugprice)
{
var maxdrug = money/drugprice;
var addtoqty;
addtoqty=prompt("How many would you like to purchase? They are $" + drugprice +" a unit. You can afford " + Math.floor(maxdrug) + ".");
if((addtoqty*drugprice)>money)
{
window.alert("Nice try you need more money to do that!")
}
else {
drugqty = parseInt(drugqty, 10) + parseInt(addtoqty, 10);
money = money - (drugprice*addtoqty);
document.getElementById(drugname+"qty").innerHTML=drugqty;
document.getElementById("money").innerHTML=money;
}
}
}
下面是我對一種特定藥物的購買按鈕。
<td><center><button onclick="buy(cocaineqty, cocaine, 'cocaine')">Buy</center></button></center></td>
當按下按鈕時,它調用該函數並正確執行。
我只需要弄清楚如何用本地函數drugqty創建的更新全局變量cocaineqty。
我試着像
drugname+"qty"=drugqty;
我的兩個想法事情,從它顯示在那裏再次解析該信息,或者以某種方式在將來使用它不止一種藥物的功能更新全局變量(再一次所以可以動態完成)
<td id="cocaineqty" align="center">0</td>
我的第一篇在這裏,但我更願意做出改變或糾正後的任何失誤較多。謝謝你的時間!
編輯:更新我的代碼的基礎上,檢查答案再次
function buy(drugqty, drugprice, drugname)
{
if (money < drugprice)
{
window.alert("You do not have enough money to do that!")
}
else if(money >= drugprice)
{
var maxdrug = money/drugprice;
var addtoqty;
addtoqty=prompt("How many would you like to purchase? They are $" + drugprice +" a unit. You can afford " + Math.floor(maxdrug) + ".");
if((addtoqty*drugprice)>money)
{
window.alert("Nice try you need more money to do that!")
}
else {
drugqty = parseInt(drugqty, 10) + parseInt(addtoqty, 10);
money = money - (drugprice*addtoqty);
document.getElementById(drugname+"qty").innerHTML=drugqty;
document.getElementById("money").innerHTML=money;
window[drugname+"qty"]=drugqty;
}
}
感謝您的幫助的正確的信息!
歡迎來到SO!數量不錯的細節和代碼片段。保持! – Veger