简体   繁体   English

JavaScript变量范围问题

[英]Javascript variable scope issue

I have a simple scoping issue that is eluding me. 我有一个简单的范围界定问题使我难以理解。

Here is a simpler version of the code but employs the same principle. 这是该代码的简单版本,但采用相同的原理。

function myFunction(){
  $('.selector_1, .selector_2').click(function(e){
    var $trgt = $(e.target);
    var myVAR;

    if ($trgt.is('.selector_1')){
      myVAR = 'selector_1';
    }

    if ($trgt.is('.selector_2')){
      myVAR = 'selector_2';
    }
    console.log(myVAR);
  }
}

The issue is, if the user were to click on selector_1 myVAR would get populated successfully every time, however, the 2nd target handler will always return myVAR as undefined. 问题是,如果用户单击selector_1 myVAR都会成功填充myVAR ,但是,第二个目标处理程序将始终将myVAR返回为未定义。

I'm assuming this is a programming 101 type thing, I have yet to find a straightforward answer, however. 我假设这是一个编程的101类型的东西,但是我还没有找到一个简单的答案。

Thanks for taking a look at this! 感谢您对此的关注! Criticism openly appreciated. 批评公开赞赏。

Your html is probably something like this: 您的html可能是这样的:

<div class='selector_1'>HELLO</div>

<div class='selector_2'><span>HI THERE</span></div> 

So when you click on the second one you get undefined bacause the target is the span and not the selector. 因此,当您单击第二个时,您将得到未定义的,因为目标是跨度而不是选择器。

Fiddle demo: http://jsfiddle.net/maniator/M6fYf/ 小提琴演示: http : //jsfiddle.net/maniator/M6fYf/

That code should work. 该代码应该工作。 Maybe e.target isn't behaving properly for some element types??? 也许e.target对于某些元素类型行为不正确??? Instead of e.target , try using this 取而代之的e.target ,请尝试使用this

function myFunction(){
  $('.selector_1, .selector_2').click(function(e){
    var $trgt = $(this);
    var myVAR;

    if ($trgt.is('.selector_1')){
      myVAR = 'selector_1';
    }

    if ($trgt.is('.selector_2')){
      myVAR = 'selector_2';
    }
    console.log(myVAR);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM