显然,我对可变范围仍然很不稳定。有什么方法可以使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
 });

最佳答案

仅当您首先单击#btn时,它将起作用,否则,该变量是未定义的。
您可以将其初始化为一个值:

var numHints = 3;


另外,您的return没有任何意义

10-06 07:33