簡體   English   中英

如何使我的程序重新運行特定的代碼行?

[英]How do I make my program re-run a certain line of code?

我正在制作游戲,並且我有js提示該人分配他們的所有技能點。 當他們受到傷害或治愈時,他們需要按一下按鈕才能更改其健康狀態值。 問題是,當他們輸入新值時,用於編輯統計信息和滾動d20的所有按鈕都消失了

作為參考,在程序開始時,玩家確定了所有狀態后,將顯示其所有狀態及其值,並滾動顯示每個狀態並編輯其​​hp值的按鈕。

這大概是我所擁有的

<script src="javascript.js">
</script>

<script>
    function hpChange() {
        var health = prompt('What is your new HP value?');
        document.write(prints all of the stats with their values);
    }
</script>

<form>
    <input type="button" onclick="hpChange()" value="Change HP"/>
</form>

(這是我與朋友一起使用自定義規則玩的DnD版本)

之前

我認為最好通過其元素來操縱文檔。 例如,您可以將統計信息表示為HTML代碼中的項目列表:

index.html:

<html>
  <body>
    <ul>
    <!-- Here we assign a unique ID to the element to get it later in our JS file -->
      <li id="hp">HP: 10</li>
      <li>STR: 5</li>
      <li>AGI: 5</li>
      <li>INT: 5</li>
      <li>CHA: 5</li>
      <li>PER: 5</li>
      <li>LUC: 5</li>    
    </ul>
     <!-- Here we assign a unique ID to the button to get it later in our JS file -->
   <button id="rollForHealth">
   Roll for Health
   </button>
   <!-- It's better to link an outer JS file at the bottom of the page to initialize it when the content is loaded -->
  <script src="javascript.js"></script>
  </body>
</html>

還有一個外部JS文件,它將更改統計信息的值:

javascript.js:

//we bind our HP element to a variable
const hp = document.getElementById('hp');
//we bind our button to its own variable
const rollForHp = document.getElementById('rollForHealth');

//create an eventlistener and bind it to the button
rollForHp.addEventListener('click', healthRoll, false);

/*
This function will bind prompt input to a variable and change
element inner HTML instead of refreshing the whole document
*/
function healthRoll() {
  let result = prompt('What is your new HP value?');
  hp.innerHTML = `HP: ${result}`
}

這就是它在jsfiddle上的工作方式

您可以對其他統計信息執行相同的操作。

希望對您有所幫助,並且您會喜歡DnD的課程。

暫無
暫無

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

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