javascript - 返回要在另一个函数中使用的变量值

时间:2015-07-27 17:48:53

标签: javascript jquery scope undefined

显然我对变量范围仍然非常不稳定。 btn2是否有办法获取由单选按钮更新的numHints的3或1的值? (目前返回undefined)。

jsfiddle

HTML:

<input id="btn" type="button" value="btn">
<br>
<form id="Difficulty">
    <input checked="checked" type="radio" name="difficulty" id="easier">Easier
    <br>
    <input type="radio" name="difficulty" id="harder">Harder</form>
</div>
<br/>
<input id="btn2" type="button" value="btn2">

JS:

 var numHints;
 $('#btn').on('click', function () {
     var difficulty = $('input[name="difficulty"]:checked', '#Difficulty').attr('id');
     if (difficulty == "easier") {
         numHints = 3;
     } else {
         numHints = 1;
     }
     console.log(numHints);
     return numHints; // doesn't work
 });

 $('#btn2').on('click', function () {
     console.log(numHints); // undefined, need numHints available in here
 });

1 个答案:

答案 0 :(得分:0)

只有先点击#btn才会有效,否则变量未定义。 您可以使用值初始化它:

var numHints = 3;

此外,您的return没有意义