Im finding jQuery to difficult to learn as there seems to be many ways to write the same thing.
As an exercise 开发者_JAVA技巧I would like to take the text within anchor tags and stuff it into the links href attribute.
eg
<a href="">http://www.something.com</a>
to become
<a href="http://www.something.com">http://www.something.com</a>
my first attemp was
<script type="text/javascript">
$(document).ready(function() {
var text = $('a').text();
$('a').attr( 'href', text );
});
</script>
which clearly doesnt work as I need to specify to do this action for each link.
Should I use a foreach loop? A .each() function? Or $this notation? Would they all work?
$('a').text()
would return the combination of every anchor nodes text value.. I just did it on stackoverflow and it gave me:
"mederlogoutaboutfaqQuestionsTagsUsersBadgesUnansweredAsk QuestionJquery $this or each() to specify one link at a timejqueryeachthiseditcloseflagchrisadd commentjqueryeachthisask your own questionjquerythiseachC++/Unix Programmer at Waterfront International Ltdjobs.stackoverflow.comquestion feedaboutfaqblogpodcastprivacy policyadvertising infocontact usfeedback always welcomestackoverflow.comserverfault.comsuperuser.commetahowtogeek.comdoctype.comcc-wikiattribution required"
Therefore you should use jQuery.prototype.each so you can save a reference to each individual anchor's text:
$('a').each(function() {
var text = $(this).text();
$(this).attr('href', text );
});
The added benefit is that each function runs in its own execution context, each variable you define, every 'text' declared is unique to that function body so there's a lot more control inside of a .each.
Regarding the vanilla loop deal - I would use jQuery.prototype.each over it because it's a higher level function, you would have to assign a variable to the length of the nodeList and start at 0, stop at the length ( or if order doesn't matter do a reverse while loop ).. this just causes more work than necessary.
精彩评论