2017-09-09 70 views
1

我想要獲取href的擴展名和主機名時,我右鍵單擊一個或元素。我曾嘗試下面的代碼,但我發現了 '未定義'jquery獲取<a>元素的主機名在右鍵單擊事件

$(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); 
      } 
     } 
    }); 

回答

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">

+0

這是輝煌的。謝謝! –

相關問題