我有这个单选按钮,如果选中,我希望它显示 2 个警报,显示 ( item="shoes"),一个来自本地,另一个来自全局,事实上警报仅显示一个意味着该变量仍然为空在全局范围内。
/*Empty item*/
var item = '';
/*Function selection item*/
function selection(select) {
var item = select;
alert(item);
}
/*If radio button selected item='shoes'*/
$('input[name="selection"]').click(function() {
if ($(this).is(':checked')) {
selection('shoes');
}
});
/*Alert on item if not empty*/
if (item !== '') {
alert(item); /*NOT WORKING*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<input type="radio" name="selection" id="shoes" value="shoes">Shoes<br>
如何将变量从局部作用域转移到全局作用域?仅当您确定另一个主题可以解决我的问题时,请不要将我标记为重复。谢谢
最佳答案
虽然这可以解决您的问题,但我建议您考虑寻找一种不涉及此类全局状态的方法。
有两个问题。首先,您在函数内重新声明了 item
变量,因此您更改了本地副本,而不是全局副本。其次,您没有在更改监听器内检查是否为空,而是仅在开始时检查。
更好的缩进可能会让这一点变得更清楚。
/*Empty item*/
var item= '';
/*Function selection item*/
function selection(select){
item = select;
alert(item);
}
/*If radio button selected item='shoes'*/
$('input[name="selection"]').click(function(){
if ($(this).is(':checked')){
selection('shoes');
}
/*Alert on item if not empty*/
if (item!==''){
alert(item); /*WORKING NOW THAT IT'S IN THE RIGHT PLACE*/
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<input type="radio" name="selection" id="shoes" value="shoes">Shoes<br>
关于Javascript - 从函数调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52538432/