PDA

View Full Version : Help with For Loop



Disco_Cowboy
01-25-2011, 03:58 AM
I have the following code which is almost completely working the way I need it to with the exception of the "downloadFile" value...


/*Regex list of download file extensions, pipe and backslash delimited. Looks for the period before the file type so it will work on download links with query parameters after it */
var downloadTypes = /\.pdf|\.doc|\.xls|\.zip|\.csv|\.ppt|\.rtf|\.pptx|\.docx|\.xlsx|\.wmv|\.mpg|\.exe|\.mp3|\.rar|\.wav/i;

/*Regex list of on-site domains, pipe and backslash delimited. */
var onsiteDomains = /\mytestdomain1\.com|\mytestdomain2\.com|javascript|#/i;

/*Used to unobtrusivly add events to objects*/
function unobtrusiveAddEvent (element,event,fn) {
var old = (element[event]) ? element[event] : function () {};
element[event] = function () {fn(); old();};
}

var links = document.links;
if ( links ){
for(var i=0; i<links.length; i++) {
if( links[i].href.match(downloadTypes) ){
unobtrusiveAddEvent( links[i], 'onclick' , function() { ntptEventTag('ev=download&eventPage=Download From: ' + escape( wa.currentDomain + wa.currentURL ) + '&downloadFile=' + escape( links[i] )); });
}
if( !links[i].href.match(onsiteDomains) ){
unobtrusiveAddEvent( links[i], 'onclick' , function() { ntptEventTag('lk=1&ev=Exit Link'); });
}
}
}

...how do I grab the value of the href that was just clicked? links[i] is not working (it's just grabbing the href value of the last href in the loop). I am missing something simple for sure. Can anyone point out what I am missing?

Thanks!

oVTech
01-25-2011, 07:35 AM
Javascript Closures?
http://xkr.us/js/closures

http://blog.morrisjohns.com/javascript_closures_for_dummies.html

https://developer.mozilla.org/en/JavaScript/Guide/Closures

Disco_Cowboy
01-25-2011, 01:56 PM
It does seem like I need a "closure" in there but man this is proving more difficult than I thought. :confused:

venegal
01-25-2011, 02:14 PM
Wrap the function in a closure:


(function (i) {
return // the original function here
})(i)

It's pretty much the first example in the first link oVTech gave you.