简体   繁体   English

为什么这样做? window.location.href

[英]Why does this work? window.location.href

Example link: http://localhost/test/page.php?success 示例链接: http://localhost/test/page.php?success

I'm curious about this. 我对此很好奇。 And I'm also new to JavaScript so it's not really a surprise but I understand the code below, I just do not know why it works away with what I seem to understand. 而且我对JavaScript还是陌生的,所以这并不奇怪,但是我理解下面的代码,我只是不知道为什么它可以解决我似乎理解的问题。 See this question for more reference. 请参阅此问题以获取更多参考。

I have this JavaScript: 我有这个JavaScript:

<script type="text/javascript">
jQuery(function($) {
    var path = window.location.href.split( '?' )[0]; 
    $('ul a').each(function() { 
        if (this.href === path) {
            $(this).addClass('sub-menu active');
            $(this).parent().closest("li").addClass('active');
            $(this).parent().parent().closest("li").addClass('active');
        }
    });
}); 
</script>

The Sidebar: 侧边栏:

<li class="sub-menu"> // Sidebar with no submenu
  <a class="" href="page1.php">
    <i class="icon-calendar"></i>
    <span>This is page 1</span>
  </a>
</li>
<li class="sub-menu"> // Sidebar with a submenu
  <a href="javascript:;" class="">
    <i class="icon-group"></i>
    <span>This has sub pages</span>
    <span class="arrow"></span>
  </a>
  <ul class="sub">
    <li><a class="" href="page2.php">This is page 2</a></li>
    <li><a class="" href="page3.php">This is page 3</a></li>
  </ul>
</li>

The code puts an active class to the menu on the sidebar which href is equals to the current url. 该代码将活动类放到侧栏菜单上,该类的href等于当前网址。 But window.location.href returns the whole url but what is inside the href's are just the page.php . 但是window.location.href返回整个URL,但是href里面的只是page.php So why does this.href === path work? 那么为什么this.href === path有效? When window.location.href.split( '?' )[0] returns http://localhost/test/page.php and the href is just page.php . window.location.href.split( '?' )[0]返回http://localhost/test/page.php而href只是page.php

The href property of an anchor is normalized to an absolute value. 锚的href属性已标准化为绝对值。

See this example: HTML: 请参见以下示例:HTML:

<a href="test.html">Test</a>

JS: JS:

var a = document.querySelector('a');
console.log(a.href);

In this instance the relative URL is being resolved to the location of the document containing the a element. 在这种情况下,相对URL被解析为包含a元素的文档的位置。 You can use the base element to control the resolution of relative URLs. 您可以使用base元素来控制相对URL的解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM