【问题标题】:window.location.hash returns hash tag in front of valuewindow.location.hash 返回值前面的哈希标记
【发布时间】:2012-10-30 16:07:12
【问题描述】:

我在 MVC3 视图中有以下代码:

 $(document).ready(function () {
    if (window.location.hash) {
        var manager= new Manager();

        manager.doSomeStuff(window.location.hash);
    }
});

有趣的是,当URL中没有hash标签,或者只有hash标签的例子:

http://localhost:1223/Index/AboutUs

http://localhost:1223/Index/AboutUs#

window.location.hash 为空且函数未执行时。 但是当哈希标签中有一些值时:

http://localhost:1223/Index/AboutUs#categoryId=5&manufacturerId=8

window.location.hash 中的值为#categoryId=5&manufacturerId=8

你能解释一下为什么#标签包含在值中,为什么当#标签后面没有值时,window.location.hash是空的。

【问题讨论】:

    标签: javascript jquery asp.net-mvc-3 url hashtag


    【解决方案1】:

    没什么好解释的。这就是它的工作方式。

    在此处阅读更多信息:http://www.w3schools.com/jsref/prop_loc_hash.asp

    定义和用法

    The hash property returns the anchor portion of a URL, including the hash sign (#).
    

    【讨论】:

    • 是的,我看到了定义,但是哈希符号与值一起返回似乎有点奇怪。这就是我问这个问题的原因。此外,当您设置 window.location.hash 值时,您不需要将井号添加到字符串中。
    【解决方案2】:

    您可以通过简单地更改哈希名称来更改它:

    //Your old hash name caught in a variable
    var nameHash = location.hash;
    
    //Your new hash name without "#"
    var newHashName = nameHash.replace("#","");
    

    【讨论】:

    • 如果哈希包含另一个 # 字符,这可能会产生不良结果。
    【解决方案3】:
    var hash = window.location.hash.substring(1);
    

    这省略了字符串的第一个字符,即哈希标记。

    【讨论】:

      【解决方案4】:

      You can repalce # 但这种方式会产生冲突并且不适用于 javascript。

      Here is window.location reference link.

      以下是不同的用法示例:

      $(document).ready(function () {
          var urlHash = window.location.hash;
          var sampleURL = '#categoryId=5&manufacturerId=8';
      
          if ( urlHash.length > 1 ) {
             //do stuff
          }else{
             //if value is empty, do stuff
          }
      
          if ( urlHash === sampleURL ) {
             commonResponse();
          }
      
          $('a').click(function() {
             var target = $(this).attr('href');
      
             if (target === sampleURL ) {
                commonResponse();
             }    
          });
      
          function commonResponse() {
             //alert('ok');
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2018-07-04
        • 1970-01-01
        • 2013-03-02
        • 2019-10-28
        • 2013-02-22
        • 2013-10-18
        • 2021-06-16
        • 1970-01-01
        • 2014-12-03
        相关资源
        最近更新 更多