示例链接:http://localhost/test/page.php?success
我对此很好奇。而且我对 JavaScript 也很陌生,所以这并不奇怪,但我理解下面的代码,我只是不知道为什么它与我似乎理解的内容不同。请参阅this question for more reference.
我有这个 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>
侧边栏:
<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>
代码将一个事件类放入侧边栏的菜单中,其 href 等于当前 url。但是 window.location.href
返回整个 url,但 href 中的内容只是 page.php
。那么为什么 this.href === path
有效呢?当 window.location.href.split( '?' )[0]
返回 http://localhost/test/page.php
并且 href 只是 page.php
.
最佳答案
anchor 的 href 属性被标准化为绝对值。
参见this例子: HTML:
<a href="test.html">Test</a>
JS:
var a = document.querySelector('a');
console.log(a.href);
关于javascript - 为什么这有效?窗口位置.href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30301888/