等于 (==) 和等于 (===) 对我不起作用

Equal (==) and equal (===) not working for me

我在 jquery 中使用 if 条件并且 == 对我和 === 都不起作用。 :( 这是我的代码:

var hash = window.location.hash;
var hash = hash.replace('#', ' ');
  alert(hash); /* Returns abc.*/
if( hash === 'abc'){
            alert(hash); /* not coming here.*/
        $('.tab').removeClass('is-active');
    }

有什么帮助吗? 提前致谢。

window.location.hash 将 return #abc 而不是 abc。所以,替换下面的代码::

var hash = window.location.hash;

有了这个::

var hash = window.location.hash.split('#')[1];

完整代码为::

var hash = window.location.hash.split('#')[1];
if( hash === 'abc'){
    $('.tab').removeClass('is-active');
}

它会起作用。

window.location.hash 将 return #abc 而不是 abc。您还删除了 #,但将其替换为 ' ',而不是 ''。尝试像这样进行比较:

var hash = window.location.hash;
alert(hash); /* Returns abc.*/
if( hash === '#abc'){
        alert(hash); /* not coming here.*/
    $('.tab').removeClass('is-active');
}

您将 # 替换为 ' ' (space) .. 因此您在散列中真正拥有的是一个“abc”而不是 "abc" ...请尝试以下

window.location.hash = "abc";
var hash = window.location.hash;
var hash = hash.replace('#', '');
  alert(hash); /* Returns abc.*/
if( hash === 'abc'){
            alert(hash); /* now comes here*/
        //$('.tab').removeClass('is-active');
    }

替换为“”而不是 space“”,它起作用了。

var hash = '#abc';
var hash = hash.replace('#', '');
  alert(hash); /* Returns abc.*/
if( hash === 'abc'){
            alert(hash); /* not coming here.*/

    }

假设当前URL是http://www.example.com/yourfile.htm#abc

var hash = window.location.hash;    // hash = #abc
if( hash === '#abc'){
    //You are in now
    $('.tab').removeClass('is-active');
}

希望这会有所帮助。