1
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())

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

提前致谢!

4

1 回答 1

1

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

尝试:

b.onclick = checkCode;

或者

b.on('click', checkCode);

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

于 2013-09-20T05:52:32.153 回答