如何执行一个基于网址哈希url#nameoffunction的js函数 [英] How to execute a js function based on url hash url#nameoffunction

查看:126
本文介绍了如何执行一个基于网址哈希url#nameoffunction的js函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些网站在URL中执行基于has的JavaScript函数。例如,当我访问 http://域名时,

。 com / jobs#test

然后网站执行基于#test的函数

I可以通过检查location.href来实现,但是有没有更好的方法?

解决方案

这就是我所做的:

  window.onload = function(){
var hash =(window.location.hash).replace('#' '');
if(hash.length == 0){
// no hash do something
}
else {
// else用hash做
}
}

演示: http://jsfiddle.net/maniator/XCjpy/show/#test

demo2: http://jsfiddle.net/maniator/XCjpy/show/

demo3: http://jsfiddle.net/maniator/XCjpy/show/#testing_again


I saw some of websites executes a JavaScript function based on has in the URL. For example,

when I access http://domain.com/jobs#test

then the website executes a function based on #test

I can do it by checking location.href, but is there a better way?

解决方案

This is what i do:

window.onload = function(){
    var hash = (window.location.hash).replace('#', '');
    if (hash.length == 0) {
        //no hash do something
    }
    else {
        //else do something with hash
    }
}

demo: http://jsfiddle.net/maniator/XCjpy/show/#test
demo2: http://jsfiddle.net/maniator/XCjpy/show/
demo3: http://jsfiddle.net/maniator/XCjpy/show/#testing_again

这篇关于如何执行一个基于网址哈希url#nameoffunction的js函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆