我几个小时前写过帖子,我有几个有趣的答案,但我不理解一切,现在我无法使用那篇文章。所以我创建了一个新的。
我在这段代码中遇到回调问题:
<div id='temp'></div>
<div id='points'></div>
<div onClick ="play(1, 1)" id='click'>clickclickclick</div>
<script>
play(function (addpoints) {
document.getElementById('temp').innerHTML = addpoints;
}());
function play (choosecolor, randescolor) {
if (choosecolor == randescolor) {
if (document.getElementById('points').innerHTML === '') {
document.getElementById('points').innerHTML=100;
}
else {
var points = function (allpoints) {
var addpoints = parseInt(allpoints) + 100;
callback(addpoints);
document.getElementById('points').innerHTML=addpoints;
}
}
points(document.getElementById('points').innerHTML);
}
}
我理解函数回调没有将var addpoint及其值发送给第二个函数,所以在第二个函数中,addpoint是未定义的。但我不明白为什么addpoints会失去它的价值(但我可以在div中显示它),回调做什么以及如何纠正它。有些用户告诉我应该选择颜色(添加点);而不是回调(addpoints);但它仍然无效。
答案 0 :(得分:-1)
<div id='temp'></div>
<div id='points'></div>
<div onClick ="play(1, 1, newcallback)" id='click'>clickclickclick</div>
这里我声明了一个newcallback函数,我会在这个方法之后调用它:
function newcallback(addpoints) {
document.getElementById('temp').innerHTML = addpoints; //undefined
});
function play (choosecolor, randescolor,callback) {
if (choosecolor == randescolor) {
if (document.getElementById('points').innerHTML === '') {
document.getElementById('points').innerHTML=100;
}
else {
var points = function (allpoints) {
var addpoints = parseInt(allpoints) + 100;
callback(addpoints);
document.getElementById('points').innerHTML=addpoints;
}
}
points(document.getElementById('points').innerHTML);
}
}
这是小提琴:JsFiddle