获取<a> element on right click event

时间:2017-09-09 17:44:14

标签: jquery event-handling

I want to get the extension and hostname of the href when I right click on a or element. I have tried the below code, but I'm getting 'undefined'

$(document).mousedown(function(e) {
        if (e.which == 3) {

            var tag = e.target.nodeName;
            var href = e.target.href;

            if (tag == 'A') {
                thelink = e.target.href;
                console.log(href.hostname);

            }
            if (tag == 'IMG') {
                thelink = e.target.src;
                console.log(href.hostname);
            }
        }
    });

1 个答案:

答案 0 :(得分:2)

您可以参考:

  

The URL interface represents an object providing static methods used for creating object URLs.

$(document).mousedown(function(e) {
    if (e.which == 3) {
        var tag = e.target.nodeName;
        var thelink = undefined;

        if (tag == 'A') {
            thelink = e.target.href;

        }
        if (tag == 'IMG') {
            thelink = e.target.src;
        }
        
        //
        // if thelink then get the hostname...
        //
        if (thelink) {
            //
            // convert string to URL
            //
            var url = new URL(thelink);
            console.log(url.hostname);
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://dummyimage.com/200x200/000/fff">