如何根据url hash执行js函数 url#nameoffunction
我看到一些网站根据 URL 中的内容执行 JavaScript 函数。例如,
当我访问 http://domain.com/jobs#test
时,网站会执行一个函数基于#test
我可以通过检查location.href来做到这一点,但是有更好的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这就是我所做的:
演示: http://jsfiddle.net/maniator/XCjpy/show/ #测试
演示2: http://jsfiddle.net/maniator/XCjpy/show/
演示3: http://jsfiddle.net/maniator/XCjpy/show/#testing_again
This is what i do:
demo: http://jsfiddle.net/maniator/XCjpy/show/#test
demo2: http://jsfiddle.net/maniator/XCjpy/show/
demo3: http://jsfiddle.net/maniator/XCjpy/show/#testing_again
如果你不需要支持像 IE6 和 IE7 这样的旧浏览器,你可以使用:
但如果你必须支持旧浏览器,你需要轮询:
If you don't need to support old browsers like IE6 and IE7 you can use:
But if you have to support older browsers you need to poll:
现场演示
注意:
eval()
很危险。您应该创建一个预定义的安全函数数组,并调用它们。Live Demo
Note:
eval()
is dangerous. You should make a predefined array of safe functions, and call those.看看这个。
参见属性表。
location.hash 应该对你有帮助。
Have a look at This.
See the property table.
location.hash should help you.
您可以使用像 YUI 这样的库来更优雅地完成此操作,看看 YUI 浏览器历史记录管理器
http: //developer.yahoo.com/yui/history/
You could use a library like YUI to do this more elegantly, Take a look at the YUI Browser History Manager
http://developer.yahoo.com/yui/history/