2017-09-09 2 views
1

Je veux obtenir l'extension et le nom d'hôte de l'href lorsque je clique avec le bouton droit sur un élément ou. J'ai essayé le code ci-dessous, mais je suis en train de 'undefined'jquery obtenir le nom d'hôte de <a> élément sur clic droit événement

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

Répondre

2

Vous pouvez consulter:

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

C'est brillant. Je vous remercie! –