Wednesday, April 29, 2009

Using Variables in jQuery

I occasionally use variables and for loops with jQuery in order to change certain items on a page. A good example of this would be my obfuscation script, modified to work for any number of obfuscated e-mails on a page.
jq(".replaceAt").replaceWith("@");

obfnum = jq(".obfuscate").length;

for(i = 0; i < obfnum; i++) {
jq(".obfuscate").eq(i).attr("href", "mailto:"+jq('.obfuscate').eq(i).text());
}
Notice the use of .eq(i). I have never had a problem with this, but the same method does not work if I were to do jq(".obfuscate:eq(i)"), which is quite necessary at times I want to change something inside of .obfuscate, and not .obfuscate itself. A quick Google search helped me find the solution:
jq(".obfuscate:eq("+i+")")

No comments: