开发者

selecting href not starting with http

using jQuery i am trying to find out all the URLS that user has entered which are not starting with http or https and finally i want to prepend htt开发者_开发百科p to all such URLs so that when user clicks on them they are taken to a proper site instead of broken link caused due to entry of URLs without http or https.

Also like to mention that User have a field "Websites they Like" where they enter websites of their interest. So if they like stackoverflow, they may end up writing www.stackoverflow.com which will be considered a relative link without http.

Also my requirments are such that i cant prompt user to enter http or https before there urls


If you're looking to "patch" the URLs of already-rendered anchor tags to include http://, you could probably run through them with something like this:

$(document).ready( function(){
    $('a:not([href^="http://"]):not([href^="https://"])').each( function(){
        $(this).attr('href', 'http://' + $(this).attr('href'));
    })
})

Edit: revised to use each(). Edit: revised to handle http and https.


I got to know what i was doing wrong i also used


$(document).ready( function(){ 
    $('a:not([href^="http://"])').attr('href', 'http://' + $(this).attr('href')); 
}) 

so the selector was working fine but 'http://' + $(this).attr('href') was not working. when i replaced $(this) with $('a:not([href^="http://"])') it worked. But now i am confused why $(this) wont work


Clean and Proper

$(document).ready( function(){
     $('a:not([href^="http://"], [href^="https://"])').each( function(){
          $(this).attr('href', 'http://' + $(this).attr('href'));
     });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜