等于(==)和相等(===)不适合我

时间:2017-03-17 13:21:57

标签: jquery hash equals-operator

我在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');
    }

有任何帮助吗? 提前谢谢。

5 个答案:

答案 0 :(得分:4)

window.location.hash将返回#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');
}

它会起作用。

答案 1 :(得分:0)

window.location.hash将返回#abc而不是abc。您还删除了#,但将其替换为' ',而不是''。尝试做这样的比较:

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

答案 2 :(得分:0)

你将#替换为''(空格)..因此你在哈希中真正拥有的是“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');
    }

答案 3 :(得分:0)

替换为''而不是空格'',它正在工作。

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

    }

答案 4 :(得分:0)

假设当前网址为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');
}

希望这会有所帮助。

相关问题