[英]Making a clickable button change text
源代码链接: http : //hexmerchant.github.io/
我希望每次单击该按钮时都显示不同的文本。 我正在使用html,css和js。
<button onclick="exploreFunction()">Explore</button>
那是按钮。 这是第一个功能。
function exploreFunction() {
var person = prompt("What is your name", "");
if (person != null) {
document.getElementById("story1").innerHTML =
"-You wake up lying on the ground. You feel a large deposit of energy inside you.";
}
}
我需要怎么做才能做到这一点?
这可以帮助多个人。 当我在这里寻找答案时,我意识到每个答案都是如此具体,以至于找不到与我的主题相匹配的内容。
我对这一切都很陌生,并试图自学……走了这么远:)
只需在按钮上添加一个ID,例如-
<button id="myButton" onclick="exploreFunction()">Explore</button>
然后,您可以向explorerFunction()添加与更改文本非常相似的命令-
document.getElementById("myButton").value = "New display text";
如果您希望每次更改文本,可以根据需要在提示符下插入名称。
function exploreFunction() { var person = prompt("What is your name", ""); if (person != null) { document.getElementById("story1").innerHTML = person + ", you wake up lying on the ground. You feel a large deposit of energy inside you."; } }
<button onclick="exploreFunction()">Explore</button> <div id="story1"></div>
如果希望故事中的文本在每次单击按钮时都发生变化,并且仅在第一次单击按钮时才显示提示,则可以使用以下方法:
var current = 0;
var person;
var story = ["-You wake up lying on the ground. You feel a large deposit of
energy inside you.", "-You go to the right.", "-The path is blocked."];
function exploreFunction() {
if (current == 0) {
person = prompt("What is your name", "");
}
if (person != null) {
document.getElementById("story1").innerHTML = story[current];
current += 1;
}
}
并为故事添加元素。 小提琴
为避免在显示故事的最后一个元素时出现任何错误,您可以删除/禁用按钮或调整功能以显示文本,例如:
if (person != null && current < story.length) {
...
为此调整了小提琴 。
此功能不是特定功能而是通用功能。 如果需要,可以使用下面的代码将此功能分配给所有按钮。 我建议您将不同的文本存储在数组中
例
<button onclick="exploreFunction(this, functionNext)" >Explore</button>
function exploreFunction(button, functionToContinue) {
var person = prompt("What is your name", "");
if (person != null) {
document.getElementById("story1").innerHTML =
"-You wake up lying on the ground. You feel a large deposit of energy inside you.";
button.onclick = functionToContinue;
}
}
function functionNext()
{
//Example code
document.getElementById("story1").innerHTML =
"-The tooth fairy really came through and you feel enchanted.";
//Other code come here
this.onclick = [new function]; //add your own function name here do not add () because it will get executed when you do, and you want it executed when the user clicks the button.
}
上面的代码做什么:
exploreFunction
添加到按钮(通过将其添加到参数来引用自身)。 exploreFunction
得到执行,提示名称,并更新story1的innerHTML。 functionNext
functionNext
时,Next将被执行。 functionNext
分配另一个onclick处理程序(由您执行)。 您正在赶上漂流吗?
由于在exploreFunction
和后续函数中都有按钮对象,因此this
变量引用按钮对象,因此可以调整此按钮的其他属性。 如值。
functionNext
Next中的示例:
this.value = "Click me to advance";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.