Bar*_*din 3 url jquery location href
我正在使用"document.location.hash"剥离网址,并尝试检查当前网址留下的内容.我不想使用任何插件,也不想学习点击等触发事件的结果.需要立即学习url变化和现代.
jQuery的:
$(function() {
$(document).location().change(function() {//this part is not working
var anchor = document.location.hash;
if( anchor === '#one' ) {
alert('current url = #one');
}else if ( anchor === '#two' ) {
alert('current url = #two');
}else if ( anchor === '#three' ) {
alert('current url = #three');
}
console.log(anchor);
});
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<a href="#one">one</a>
<a href="#two">two</a>
<a href="#three">three</a>
Run Code Online (Sandbox Code Playgroud)
深注:我已经阅读了这些问题并且cout找到了我要找的内容: 如何检测JavaScript中的URL更改 + 如何更改javascript中的当前URL?
不使用jQuery以外的插件,您可以处理'hashchange'事件:
$(document).ready(function() {
$(window).bind( 'hashchange', function(e) {
var anchor = document.location.hash;
if( anchor === '#one' ) {
alert('url = #one');
}else if ( anchor === '#two' ) {
alert('url = #two');
}else if ( anchor === '#three' ) {
alert('url = #three');
}
console.log(anchor);
});
});
Run Code Online (Sandbox Code Playgroud)
与后备一起使用:您应该使用Modernizr来检测是否支持hashchangeEvent,如果该支持检查失败,则回退到Ben Alman的jQuery hashchange事件插件,并在您的else块中使用@Baylor Rae的解决方案.