Javascript - 从函数调用变量

标签 javascript jquery

我有这个单选按钮,如果选中,我希望它显示 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/

相关文章:

javascript - 如何将所选选项从 select_tag 发送到 onchange javascript 函数

jquery UI 库和 extjs、dojo/dijit、YUI 一样全面吗?

javascript - 从外部 json 文件获取对象数组并在 javascript 中存储为数组

javascript - 获取拆分字符串的索引

javascript - 为什么一个组件的多个实例共享相同的状态?

javascript - Angular 4 在绑定(bind)时将表单输入值更改为#

jquery - 如何根据当前元素的属性设置 jQuery 插件选项?

javascript - css - bootstrap carousel 依赖项,需要导入哪些文件才能工作

带有 "bubble buttons"的页面之间的 Jquery 移动滑动

javascript - Image.onload 回调触发不一致