简体   繁体   中英

JavaScript get href onclick

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?

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/

如果你在链接中放入一个href,它只会链接到它,将href属性更改为data-link,然后获取该属性,js应该可以工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM