显然我对变量范围仍然非常不稳定。 btn2
是否有办法获取由单选按钮更新的numHints
的3或1的值? (目前返回undefined
)。
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
});
答案 0 :(得分:0)
只有先点击#btn
才会有效,否则变量未定义。
您可以使用值初始化它:
var numHints = 3;
此外,您的return
没有意义