我试图让这个脚本运行addEventListener。 如果单击该按钮,则应从阵列中获取随机文本。 但是,我不是一个javascript王。请帮帮我。
function GetValue()
{
var whys = new Array(
"why 1",
"why 2",
"why 3"
);
var random = whys[Math.floor(Math.random() * whys.length)];
var btn = document.getElementById("message");
btn.addEventListener("click", GetValue, false);
}

<span class="why_title" id="message">Ask Why!<br/>And Ask it Again<br/>And again</span>
<button class="why_btn" onclick="GetValue();">Ask Why Again!</button>
&#13;
答案 0 :(得分:1)
首先你要定义&#39; btn&#39; GetValue&#34;函数&#34;之外的变量范围。 并使用全局范围内的EventListener,以便在按钮单击时调用该函数。
var btn = document.getElementById("why_btn");
function GetValue()
{
var whys = new Array(
"why 1",
"why 2",
"why 3"
);
var random = whys[Math.floor(Math.random() * whys.length)];
document.getElementById('message').innerHTML += '<br>' + random;
}
btn.addEventListener("click", GetValue);
&#13;
<span class="why_title" id="message">Ask Why!<br/>And Ask it Again<br/>And again</span>
<button id="why_btn">Ask Why Again!</button>
&#13;
答案 1 :(得分:0)
我发现需要在JavaScript代码中修改几件事情:
addEventListener - 使用错误元素绑定:
<button class="why_btn" onclick="GetValue();">Ask Why Again!</button>
已从JavaScript处理点击事件,因此请从按钮标记中删除onclick
属性。
您的JavaScript代码段:
var btn = document.getElementById("message");
btn.addEventListener("click", GetValue, false);
btn.addEventListener("click", GetValue, false);
- 在函数
解决方案:
function GetValue() {
var whys = new Array(
"why 1",
"why 2",
"why 3"
);
var random = whys[Math.floor(Math.random() * whys.length)];
document.getElementById("message").innerHTML = random;
}
//var btn = document.getElementById("message");
var btn = document.querySelector(".why_btn");
btn.addEventListener("click", GetValue, false);
&#13;
<span class="why_title" id="message">Ask Why!<br/>And Ask it Again<br/>And again</span>
<button class="why_btn">Ask Why Again!</button>
&#13;
希望它有用:)
答案 2 :(得分:-2)
您正在向文本添加事件侦听器,而不是按钮。
function GetValue()
{
var whys = new Array(
"why 1",
"why 2",
"why 3"
);
var random = whys[Math.floor(Math.random() * whys.length)];
alert(random);
}
var btn = document.getElementById("message");
btn.addEventListener("click", GetValue, false);
&#13;
<span class="why_title">Ask Why!<br/>And Ask it Again<br/>And again</span>
<button id="message" class="why_btn" onclick="GetValue();">Ask Why Again!</button>
&#13;