简体   繁体   中英

Jquery else if statement

I came up with some jquery to come from an external page and to show the hidden div (#section2) on another page. The problem is that I can't seem to get #section3 to work the same as #section2. Here's the code.

jQuery(document).ready(function() {
    var hash = window.location.hash.substring(0);
    jQuery(hash).css({
        "display": "block"
    });
    if (hash != '#section2') {
        jQuery('#section1').css({
            "display": "block"
        });
    }
    else {
        jQuery('#section1').css({
            "display": "none"
        });
    }
});​

I tried else if if(hash != '#section3'){ jQuery('#section1').css({"display":"block"}); } if(hash != '#section3'){ jQuery('#section1').css({"display":"block"}); } I can only seem to get either #section2 or #section3 to appear with section1 hidden when their respective urls with the hash are entered. I can't seem to get them both of them to function correctly at the same time. Basically I need some thing that will produce if(hash != '#section2' or '#section3') . I'm learning so any help would be much appreciated.

jQuery(document).ready(function() {
    var hash = window.location.hash.substring(0);
    jQuery(hash).css({
        "display": "block"
    });
    if (hash != '#section2' && hash != '#section3') {
        jQuery('#section1').css({
            "display": "block"
        });
    }
    else {
        jQuery('#section1').css({
            "display": "none"
        });
    }
});​

Also, look into using the jQuery .show() and .hide() instead of those css changes (same effect, but less wordy, and it remembers the previous state).

Try;

$(document).ready(function(){
  var sectionhash = window.location.hash.substring(0);
  $(hash).css({"display":"block"});
  if(hash != '#section2' || hash != '#section3'){
    $('#section1').css({"display":"block"});
  }else {
    $('#section1').css({"display":"none"});
  }
});

OR

$(document).ready(function(){
  var sectionhash = window.location.hash.substring(0);
  $(hash).css({"display":"block"});
  if(hash != '#section2'){
    $('#section1').css({"display":"block"});
  }else if(hash != '#section3'){
    $('#section1').css({"display":"block"});
  }else {
    $('#section1').css({"display":"none"});
  }
});
(function($) {
    var hash = window.location.hash;
    $(hash).css('display', 'block');
    $("#section1").toggle(!(hash=='#section2'||hash=='#section3'));
})(jQuery);​

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