gpt4 book ai didi

javascript - 如何让我的程序重新运行某行代码?

转载 作者:行者123 更新时间:2023-11-30 14:06:58 26 4
gpt4 key购买 nike

我正在制作游戏,我有 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 版本,我用自定义规则和 friend 一起玩)

before

after

最佳答案

我认为通过元素来操作文档会更好。例如,您可以在 HTML 代码中将统计信息表示为项目列表:

索引.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 中的 session 。

关于javascript - 如何让我的程序重新运行某行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55193205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com