简体   繁体   中英

Why my IF isn't working properly?

I'm coding a function to get the "data-screen" attribute of a clicked element (if there's any to get) and take some action based on whether the currently active screen is same as or different from that of the clicked element.

The problem is my If check for undefined works alright but ignores the second condition:

  • If I click elsewhere on the page: nothing. :D
  • If I click on the Home link: nothing. :D
  • If I click on the New Quest: it writes on console. :(

Thanks for any help! Here is my code:

HTML

<li><a data-screen="home" href="#">Home</a></li>
<li><a data-screen="new-quest" href="#">New Quest</a></li>

<div id="container" data-screen="new-quest"></div>

JAVACSCRIPT

function getScreen(){
    var body = $('body'),
        activeScreen = $('#content').attr('data-screen'),
        screen;
    body.on('tap',function(e){
        screen = $(e.target).attr('data-screen');
        if(screen != undefined && screen != activeScreen){
            console.log('Target <data-screen>: ' + screen);
            console.log('Active Screen: ' + activeScreen);
        }
     });
}

The condition is supposed to be like this:

screen get the data-screen value for the clicked element. FIRST CONDITION: If screen is undefined , cause the element doesn't have the attribute the stop or else keep going. SECOND CONDITION: If the first check is OK, it has some "screen" on it, check if the screen is DIFERENT from the activeScreen which is an attribute for the page container.

Because if they DIFERENT I can render another content for the page. But they are EQUALS and it keeps writing on console, even when it should stop.

Actually, your code (apart from a typo) is working as intended, as proven in this fiddle:

http://jsfiddle.net/LgMYd/

Change <div id="content" data-screen="home"> to <div id="content" data-screen="new-quest"> to test the other case.

Edit: I did fix the typo that's mentioned in the answer above, but I think that was just a typo you made when removing all the $'s.

Also, as said in the comments, the active screen will only be determined ONCE on document ready. IF you are creating a single page application, this will not work the way you expect it to! In that case, you would have to update the active screen variable each time a new view is loaded.

Typo in your variable? A stray $ perhaps?

screen != undefined && $screen != activeScreen

to become

screen != undefined && screen != activeScreen

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