Passing on variables to functions

Subscribe to Passing on variables to functions 5 posts, 3 voices

 
dob Scriptwright

Hey there,

I have the following problem:


var links = document.getElementsByTagName("a"), urls = new Array();
for (var i=0; i<links.length; i++) {
	if (links[i].href.match(/imdb\.com\/title\//gi)) {
		GM_xmlhttpRequest({
			method: "GET",
			url: links[i].href,
			onload: function(e) {
				var title = e.responseText.split("<title>")[1].split("</title>")[0];
				links[i].setAttribute("title", title);
			}
		});
	}
}

Now I get the error message "links[i] has no properties".
I kind of know why, I didn't define links[i] during the onload function. But unfortunately, I don't really know how to pass on that variable and/or Array to my function during the XHR.

Any ideas?
Thanks.

 
Mikado Scriptwright

			onload: rs(i)
		});
	}
}
function rs(i) {
	return function(e) {
		var title = e.responseText.split("<title>")[1].split("</title>")[0];
		links[i].setAttribute("title", title);
	};
}

 
dob Scriptwright

Thanks a lot, works like a charm.

 
Mikado Scriptwright

BTW, why would you need "g" flag in the regexp? I'd rewrite it that way:

var links = document.links, urls = new Array(), re = /imdb\.com\/title\//i;
for (var i=0; i < links.length; i++) {
	if (re.test(links[i].href)) {

 
Joel H Scriptwright

The 'g' flag shouldn't make much of a difference, as the regex should only appear once in the string. If it does appear twice for some reason, then it would replace it in both places and Mikado is right. In general, though, it's unlikely that it will matter.

-Joel