是否可以从锚标记调用 Javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7814725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to call Javascript from an anchor tag?
提问by Philip Kirkbride
Possible Duplicate:
Handle URL anchor change event in js
可能的重复:
处理 js 中的 URL 锚点更改事件
Is it possible to have a javascript function run via an anchor tag.
是否可以通过锚标记运行 javascript 函数。
E.g. if you went to... www.site.com/index.html#function1 ... Then function1 would run?
例如,如果您访问... www.site.com/index.html#function1 ... 那么 function1 会运行吗?
采纳答案by RobG
Put a an onload listener on the page and a click listener on the link that goes to the anchor. When fired, check window.location.href, something like:
在页面上放置一个 onload 监听器,在指向锚点的链接上放置一个点击监听器。触发时,检查 window.location.href,类似于:
<body onload="checkHash();">
<a href="#foo" onclick="checkHash()">go to foo</a>
<br>
<a href="#bar">go to bar</a>
<p>something in between</p>
<a name="foo">foo</a>
<br>
<a name="bar">bar</a>
<script type="text/javascript">
function checkHash() {
// Check URL using setTimeout as it may not change before
// listener is called
window.setTimeout(doHashCheck, 10)
}
var doHashCheck = (function(global) {
return function() {
var fnName = window.location.hash.replace(/^#/,'');
console.log(fnName);
// fnName should be a native function, not a host method
if (typeof global[fnName] == 'function') {
global[fnName]();
}
}
})(this);
function foo() {
alert('foo');
}
if (!window.console) window.console = {};
if (!console.log) console.log = window.alert;
</script>
</body>
回答by Justin Lucas
You can't do that by simply including it in the anchor tag but you could use the hashtag (location.hash
) in order to call your function
您不能通过简单地将其包含在锚标记中来做到这一点,但您可以使用井号 ( location.hash
) 来调用您的函数
回答by Randy Burden
$(document).ready(function() {
//Get hash from URL. Ex. index.html#Chapter1
var hash = location.hash;
if (hash == '#Chapter1') {
//Do stuff here
}
});
回答by Matt H
You can't call the javascript like that, but if you control the other site, you can check the URL in the body Load event, then execute a script.
你不能那样调用javascript,但是如果你控制了其他站点,你可以检查body Load事件中的URL,然后执行一个脚本。