【问题标题】:Appending Button not working附加按钮不起作用
【发布时间】:2013-09-20 13:53:30
【问题描述】:
function story1(){
var t=document.createElement('p');
t.innerHTML = "You wake up from your sleep in a half daze to hear noises of screams outside your bedroom window. You stumble over there to see what is the matter. You decide it's a good idea to grab your"+' <i onclick=addSword()> '+" sword "+' </i> '+"as you take the "+' <i onclick=story2()> '+" stairs. "+'</i>';
document.getElementById("story").appendChild(t);
}

function story2(){
var t = document.createElement('p');
t.innerHTML = "You realize that the door is locked and need to break the code in order to go outside." +' <i id="one" onclick=addOne()> '+ num1 +'</i>'+' <i id="two" onclick=addTwo()> '+ num2+'</i>'+' <i id="three" onclick=addThree()> '+ num3 +'</i>';
document.getElementById("story").appendChild(t);
var b = document.createElement('input');
b.type = 'button';
b.value = 'Check Code';
b.onclick = checkCode();
document.getElementById("story").appendChild(b);
}

简而言之,这两个功能是我的问题所在。我正在尝试在 div 内附加一个按钮以检查代码是否损坏。 checkCode 的编码按原样工作。

问题是,checkCode() 在单击楼梯而不是按钮时实际上正在工作。我试过b.on('click', checkCode())b.setAttribute('onclick', checkCode())

也许我没有正确编写按钮,但教程和阅读类似问题的答案只能让我到目前为止! (笑)

提前致谢!

【问题讨论】:

    标签: javascript button append


    【解决方案1】:

    您的问题是您将函数 checkCode 的结果设置为处理程序/属性而不是函数引用。你正在调用它。

    试试:

    b.onclick = checkCode;
    

    b.on('click', checkCode);
    

    您需要将函数的引用设置为处理程序。用() 设置它会在那时和那里调用函数,因此你会看到行为。

    【讨论】:

    • 谢谢!简直不敢相信只是那些愚蠢的括号把我搞砸了。
    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多