I'm reading 'JavaScript Missing Manual' and there is this script that automatically adds URL of a link next to this link itself.

$('a[href^="http://"]').each(function(){
    var href = $(this).attr('href');
    href = href.replace('http://', '');
    $['a'].after(' (' + href + ') ');
}); // end each

The problem is that it doesn't work at all. Could someone please explain me what's wrong with this code?

有帮助吗?

解决方案

Change this line

$['a'].after(' (' + href + ') ');

to

$('a').after(' (' + href + ') ');

$ should be called as a function, not an array.

Although looking at your code, you probably want this instead:

$(this).after(' (' + href + ') ');

edit:

here is the full code:

$('a[href^="http://"]').each(function(){
var href = $(this).attr('href');
href = href.replace('http://', '');
$(this).after(' (' + href + ') ');
}); // end each

其他提示

May I suggest a similar, but shorter, version?

$('a[href^="http://"]').each(function(){
    $(this).after(" ("+$(this).attr('href').replace("http://",'')+")");
}); // end each

Pretty much fmsf's solution + a small modification to make the code a bit shorter. o/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top