2017-09-09 3 views
1

aまたは要素を右クリックすると、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

これは素晴らしいです。ありがとうございました! –

関連する問題