簡體   English   中英

Function 參數問題與變量和字符串有關

[英]Function parameters issue with variables and strings

我正在開發一個簡單的 農場游戲,並且遇到重復代碼的問題。 我必須為每個項目做出不同的收獲 function,並且隨着添加的蔬菜越來越多,做出改變變得越來越困難。 我試圖用 function 參數解決這個問題,但我收到了這個錯誤。

index.html:12 Uncaught ReferenceError: peas is not defined
    at HTMLButtonElement.onclick (index.html:12)

這是 HTML:

<div class="plot" id="plot1">
  <button id="grow1" onclick="plantPeas()">Grow Peas!</button> 
  <button id="harvest1" onclick="harvest(peas, 1)">Harvest Peas!</button>
</div>

這是 JavaScript

let plotStatus = {
   peas: "empty",
}
function harvest(veg, num) {
   plotStatus.veg = "empty";
   document.getElementById("grow" + num).style.opacity = "1";
   document.getElementById("harvest1" + num).style.opacity = "0";
   document.getElementById("harvest1" + num).style.zIndex = "-1";
   produce.veg++;
}
function plantPeas() {
   // Set timeout for growingPeas and  readyPeas
   setTimeout(growingPeas, 2000); // Change the status if peas to growing in 2 seconds
   setTimeout(readyPeas, 5000); // Change the status of peas to ready in 5 seconds
   // Remove the grow peas button
   peaPlntBtn.style.opacity = "0";
}

我知道它希望 peas 是一個變量,但它也不能作為字符串工作。

謝謝你。

由於您正在嘗試簡化,您根本無法使用 ID,而只需引用父 object 和數據屬性。

 let plotStatus = {corn:"empty",peas: "empty"} let produce = {corn: 0,peas: 0} function plant(el){ plot = el.parentNode; veg = plot.dataset.produce; switch(veg){ case "peas": plantPeas();break; } } function harvest(el) { plot = el.parentNode; veg = plot.dataset.produce; plotStatus[veg] = "empty"; plot.querySelector(".grow").style.opacity = "1"; plot.querySelector(".harvest").style.opacity = "0"; plot.querySelector(".harvest").style.zIndex = "-1"; produce[veg]++; console.log(produce, plotStatus); }
 <div data-produce="peas" class="plot"> <button class="grow" onclick="plant(this)">Grow Peas!</button> <button class="harvest" onclick="harvest(this)">Harvest Peas!</button> </div> <div data-produce="corn" class="plot"> <button class="grow" onclick="plant(this)">Grow Corn!</button> <button class="harvest" onclick="harvest(this)">Harvest Corn!</button> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM