Html JavaScript 获取 href onclick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17807929/
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
JavaScript get href onclick
提问by Callum Whyte
I am trying to return the href
attribute of a link using JavaScript when the user clicks on it. I want the URL the link is linking to displayed in an alert instead of loading the page.
href
当用户单击它时,我试图使用 JavaScript返回链接的属性。我希望链接所链接的 URL 显示在警报中,而不是加载页面。
I have the following code so far:
到目前为止,我有以下代码:
function doalert(){
alert(document.getElementById("link").getAttribute("href"));
return false;
}
With the following markup:
使用以下标记:
<a href="http://www.example.com/" id="link" onclick="return doalert()">Link</a>
For some reason, no alert is ever displayed and the page loads instead.Does anyone know why this is?
出于某种原因,没有显示任何警报,而是加载页面。有人知道为什么是这样吗?
Using jQuery is not an option in this case.
在这种情况下,使用 jQuery 不是一种选择。
回答by jenson-button-event
Seems to be the order of your code, try this
似乎是你代码的顺序,试试这个
<script>
function doalert(obj) {
alert(obj.getAttribute("href"));
return false;
}
</script>
<a href="http://www.example.com/" id="link" onclick="doalert(this); return false;">Link</a>
回答by Mark Redman
if you put an href in the link, it will just link to it, change the href attribute to data-link and then get that attribute and the js should work.
如果你在链接中加入一个 href,它只会链接到它,将 href 属性更改为 data-link,然后获取该属性,js 应该可以工作。