...

View Full Version : indexOf() function with a variable string?



WhatABoringName
11-14-2012, 09:28 PM
Greetings,

for the following webpage I created a piece of Javascript to fill in the missing images: Link (http://www.last.fm/user/lastfmprojeKct/library/music/King+Crimson?sortOrder=desc&sortBy=plays)


var imageGet = document.getElementsByClassName('art');
var i = imageGet.length;
var a;

while (--i>=0)
{

a = imageGet[i].parentNode.parentNode.getAttribute('href');


if (a.indexOf('/Larks%27+Tongues+in+Aspic') > -1)
{
imageGet[i].src = 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/64%20x%2064/ltia.jpg'
};


if (a.indexOf('/Three+of+a+Perfect+Pair') > -1)
{
imageGet[i].src = 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/64%20x%2064/3oapp.jpg'
};

};

While this actually does what is supposed to happen, I was wondering if there's a neater way of including more possible strings for the indexOf()-function, without making a new 'if'-statement for every piece of string I'd want to include eventually.

Thanks for taking the time to read this.

Cheers!

Old Pedant
11-14-2012, 10:27 PM
Since it seems that each "if" test has to then produce a different URL for the .src property, I don't see how you can avoid doing one "if" per string with one URL per "if".

But at least you could do it using an array:



var addPics = [
[ "/Larks%27+Tongues+in+Aspic", "ltia.jpg" ],
[ "/Three+of+a+Perfect+Pair", "3oapp.jpg" ],
... add as many more as needed ...
]
var baseURL = "http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/";

while (--i>=0)
{
var image = imageGet[i];
var a = image.parentNode.parentNode.getAttribute('href');
for ( var p = 0; p < addPics.length; ++p )
{
if (a.indexOf( addPics[p][0] ) >= 0 )
{
image.src = baseURL + addPics[p][1];
break; // out of for loop...presumably you will only change image.src once
}
}
}

WhatABoringName
11-14-2012, 10:47 PM
That's what I needed, makes for a cleaner list to manage. Much appreciated!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum