我想做的是只运行一次if语句并禁用该语句。在我的代码中,如果我连续单击按钮,则if语句仍会呈现。这是为什么?
HTML:
<button onclick="appendMsg()">submit</button>
<div id="wrapper"></div>
Javascript:
function appendMsg(){
var triggerOnceforShare = true;
if(triggerOnceforShare){
triggerOnceforShare = false;
document.getElementById('wrapper').innerHTML+=triggerOnceforShare + "<br />"
console.log(triggerOnceforShare);
}
}
Codepen:
http://codepen.io/vincentccw/pen/uoBkI
最佳答案
您应该将var triggerOnceforShare = true;
放在全局函数之外,它将起作用。
var triggerOnceforShare = true;
function appendMsg(){
if(triggerOnceforShare){
triggerOnceforShare = false;
document.getElementById('wrapper').innerHTML+=triggerOnceforShare + "<br />"
console.log(triggerOnceforShare);
}
}