简体   繁体   中英

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.

I'm assuming this is a programming 101 type thing, I have yet to find a straightforward answer, however.

Thanks for taking a look at this! Criticism openly appreciated.

Your html is probably something like this:

<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/

That code should work. Maybe e.target isn't behaving properly for some element types??? Instead of e.target , try using 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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