【发布时间】:2016-11-18 20:18:10
【问题描述】:
我正在尝试制作一个简单的 HTML 页面,其中包含一个带有一些类的段落和一个带有将从数组中选择的随机预定义名称的按钮,以及另一个显示结果的段落。
我创建了一个函数来检查按钮的名称是否在第一段中作为类存在,如果存在,它将在最后一段中写入“它存在。”。如果不是,它将显示“不,它没有。”。
当我点击按钮时,该功能将被触发。它只工作一次的问题。这是代码
var mainParagraph = document.getElementById("test-paragraph"),
buttonCheck = document.getElementById("class-checker"),
resultContainer = document.getElementById("result-container");
// An array of possible names of the button
var buttonName = ["test", "two", "random", "fly", "false", "checked", "wrong", "last", "process", "end"],
x = Math.random() * 10,
z = Math.floor(x);
//change the button's name each time the button is clicked. "not working."
function butonClicked() {
'use strict';
buttonCheck.textContent = buttonName[z];
}
// function to check if button's name is the same as a class in the first paragraph
function checkTheClass() {
'use strict';
if(mainParagraph.classList.contains(buttonName[z])) {
resultContainer.textContent = "yes the class exists. It's : " + '"' + buttonName[z] + '"';
} else {
resultContainer.textContent = "No the class doesn't exists.";
}
}
// Trigger the function when the button is clicked
buttonCheck.onclick = function() {
'use strict';
butonClicked();
checkTheClass();
};
<html>
<body>
<p id="test-paragraph" class="test random checked work done process"> This is a random text to be use for the test
<br/> these are the classes: test, random, checked, work, done, process. </p>
<button id="class-checker">click!</button>
<p id="result-container">Here is the result</p>
</body>
</html>
我已经检查了这些答案,但我仍然无法解决问题:
Simple onclick event worked only once.
onclick event works only once in arctext script.
这是 Codepen 中的代码:http://s.codepen.io/Noureddine/debug/JbbBQX。
Ps:我不知道JQquery
【问题讨论】:
-
那么你只执行一次随机部分。如果你想让它再次执行,你需要把那个逻辑移到里面。
-
对不起,我没听懂。您能否解释更多或提供一个链接,我可以阅读更多内容,因为我在 JavaScript 方面并不先进。感谢您的回复。
标签: javascript