开发者

finding links that are hyper-links in jQuery

Im trying to take a link either when clicked or hover over be able to grab the attribute href and tell if its a hyper-link or not. Also i want it to be able to tell me if its a hyper-link to my own site. Plus various other filters.

The main purpose for this is so that when a internal link is clicked it will tell ajax to grab the content, alot of my links are generated (via wordpress)so I can't modify them too much. Another purpose for this is so i can also make all external links open on a new window.

I have a solution that works on a simple test page but when i put into a working page it breaks. I know i am probably making this harder then it should be.

Here is my code

$(function(){
   $('a').live('click', function(){
      var x = $(this).attr('href');

      $(this).parent('div').append('<div id="test">' + x +'</div>');
      $('#test:contains("http")').css('color', 'red');
      $('#test:contains("sitename")').css('color', 'black');
      $('#test:contains("admin")').css('color', 'red');
      if($('#test').css('color') == 'red'){

         alert('external link');
         $('#test').remove();
         return true; 

      }else{

         alert('external link'开发者_开发知识库);
         $('#test').remove();
         return false;

      }
   });
});

thanks for you help


$('a').live('click', function(){
   var href = $(this).attr('href');

   if(/http:\/\//.test(href) || /admin/.test(href)){
      //alert('external link');
      $(this).attr('target', '_blank');
      return(true);
   }

   if(/sitename/.test(href)){
      //alert('internal link');
      $.ajax({});
      return(false);
   }       
}

that is a better approach I guess. Should work, but untested. The regex can/and should be fine tuned.


You could also use the jQuery selector syntax (http://api.jquery.com/attribute-starts-with-selector/):

$('a[href^=http://], a[href^=/admin/]').live('click', function(){});
$('a[href^=/sitename/]').live('click', function(){});

If you checkout the selector API you'll find some more selectors (e.g. ends with X, contains X, etc.).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜