【问题标题】:JS scope: accessing variable [duplicate]JS范围:访问变量[重复]
【发布时间】:2013-06-24 15:26:08
【问题描述】:

我知道这个问题已经被问过很多次了,但形式不同。我想在最顶层函数范围内的其他地方访问selected 变量(alert 当前返回未定义)。我知道我需要以某种方式使用return。提前谢谢你。

$('#people_search_mobile').change(function() {

  var selected;

  $('li a', $('#suggestions')).bind('click.autocomplete',function(){ 
    selected = ($(this).text());
  });

  alert(selected);

}

【问题讨论】:

    标签: javascript jquery scope


    【解决方案1】:

    这没有任何意义。当alert 发生时,li a 尚未被点击。 alert始终显示undefined,为selected 赋值的代码尚未运行,并且可能永远不会运行 .

    如果你想提醒这个值,你需要在li a被实际点击的时候这样做:

    $('#people_search_mobile').change(function() {
    
      var selected;
    
      $('li a', $('#suggestions')).bind('click.autocomplete',function(){ 
        selected = ($(this).text());
        alert(selected);
      });
    
    
    }
    

    【讨论】:

    • 好的,但是如果我想将此值传递给 '.bind' 之外的另一个函数,那么最好的方法是什么?
    • @PaulOsetinsky 将该代码移到事件处理程序中,我已将 alert 放置在其中。
    【解决方案2】:

    Meagar 是正确的,但是我发现有时在其他地方编写函数会有所帮助,这样我就可以保持事件处理程序的清洁。

    $('#people_search_mobile').change(function() {
    
      var selected, myClickHandler;
    
      myClickHandler = function(){
        selected = ($(this).text());
        alert(selected);
      };
    
      $('li a', $('#suggestions')).bind('click.autocomplete', myClickHandler);
    
    }
    

    编辑:或者如果您想将选定的值传递给别处的另一个函数...

      myClickHandler = function(){
        selected = ($(this).text());
        showMyAlert(selected);
      };
    
    ...
    
    function showMyAlert(selected){
      alert(selected);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多