如何从另一个函数调用使用window.onload的函数

时间:2018-10-29 11:35:08

标签: javascript function return

一旦用户单击一个调用myFunction的按钮,我就尝试再次使用questionFunction(),但出现错误“ questionFunction未定义”

window.onload = function questionFunction() {
  var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}

function myFunction() {
return questionFunction();
}

我不想在加载时更改文本,而且一旦用户单击以调用myFunction()时也将再次更改

3 个答案:

答案 0 :(得分:1)

您会收到此错误,因为函数 expression 不会在该函数出现的范围内添加该函数的标识符(只有函数 declarations 会这样做)。

简单的答案是改用函数声明:

function questionFunction() {
  var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}
window.onload = questionFunction;

由于已为函数添加了标识符,因此您现在可以像在myFunction中那样调用它。

答案 1 :(得分:1)

只需声明questionFuntion,然后在需要的地方重复使用此功能

function questionFunction() {
    var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}
window.onload = questionFunction;

function myFunction() {
    return questionFunction();
}

答案 2 :(得分:0)

function questionFunction() {
  var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}

window.onload = questionFunction;

function myFunction() {
  return questionFunction();
}

这将起作用。 由于功能范围错误,您会收到错误消息。

您可以在此处阅读有关内容:

https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/