如何将一个JavaScript函数回调为多个函数?

时间:2016-05-18 11:00:45

标签: javascript function callback

我有一些JavaScript函数,如下所示: -



function temp() {
    var rep ="some";
}



function solve() {
  function temp();
  $("#demo").text('solve1:'+rep);
}

function solve1() {
  function temp();
  $("#demo1").text('solve2:'+rep);
}
  
function solve2() {
  function temp();
  $("#demo2").text('solve3:'+rep);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<button onclick="solve()">solve</button><br>
<button onclick="solve1()">solve</button><br>
<button onclick="solve2()">solve</button><br>
&#13;
&#13;
&#13;

我的问题是如何首先将function temp()回调到所有其他三个函数中。上面的脚本不起作用。如何在多个函数中包含一个JavaScript函数?

1 个答案:

答案 0 :(得分:1)

首先,您需要从rep函数返回变量temp()的值。然后,只要您调用该函数,该值就可用。请注意,调用该函数时,您不必使用关键字function。只是函数的名称就可以了。请参阅代码注释以便更好地理解。

&#13;
&#13;
function temp() {
    var rep = "some";
    return rep;        // Return the value of the 'rep' variable.
}



function solve() {
  var rep = temp();        // Call the 'temp()' function defined above.
  $("#demo").text('solve1:'+rep);
}

function solve1() {
  var rep = temp();
  $("#demo1").text('solve2:'+rep);
}
  
function solve2() {
  var rep = temp();
  $("#demo2").text('solve3:'+rep);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<button onclick="solve()">solve</button><br>
<button onclick="solve1()">solve</button><br>
<button onclick="solve2()">solve</button><br>
&#13;
&#13;
&#13;