JavaScript获取href onclick [英] JavaScript get href onclick

查看:99
本文介绍了JavaScript获取href onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户点击链接时使用JavaScript返回链接的 href 属性。我希望链接链接的URL显示在警报中,而不是加载页面。

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.

到目前为止,我有以下代码:

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?

在这种情况下使用jQuery不是一种选择。

Using jQuery is not an option in this case.

推荐答案

似乎是您的代码的顺序,试试这个

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>

http://jsfiddle.net/YZ8yV/

http://jsfiddle.net/YZ8yV/2/

这篇关于JavaScript获取href onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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