views:

39

answers:

1

Still trying to learn the basic of jquery so in the weekend I started looking on simple rewriting of links in greasemonkey. The script is working but it's not looping. It just take the url from the first .img and and write it into all the other .img instead of getting the each link and write it into the same element. Not sure if it made any sense but take a look at the script and I'm sure you understand. :)

   function rewrite() {
   $.each($(".img"),function(){
   var a=$("a img[src*='/SAN/']").attr('src');
   $("a img[src*='/SAN/']").parent().attr('href','http://somesite.com/'+a);
});
}
+1  A: 

It looks like this is what you're after:

function rewrite() {
  $("a img[src*='/SAN/']").each(function() {
    $(this).parent().attr("href", 'http://somesite.com/'+this.src);
  });
}

This loops through each image and sets the parent <a> href property based on the src of the current image you're looping over, using this inside that .each() loop is the key here. Otherwise .attr() gets the attribute from the first element it matches, rather than the current element you're looping over.

Nick Craver
Thank you Nick. More or less what I was looking for. Think I should be able to make a final result with this info. I'm working on getting just part of the src url. Like this.
Bulfen
var a=$("a img[src*='/SAN/']").attr('src');var n=a.substring(a.indexOf('/SAN/')+26,a.length-4);
Bulfen
Ahh.. Got it. Just use "this.src.substring"
Bulfen
@Bulfen - Ah yes...was on the phone trying to figure out what you were after there, always go from `this` when getting a property in a loop :)
Nick Craver
Yep. It works perfect now. Thank you for the help Nick. ;) Saved me from some headaik. :D
Bulfen
@Bulfen - welcome :) glad you got it like you wanted.
Nick Craver