javascript - Overkill? Using indexOf() to discover contents of a string -
i'm learning javascript (fun!) beginning javascript, , particular example in book seems overkill. know things aren't strictly best practice - using document.write - make examples extremely easy understand. seems case of opposite: they're using seems complicated way of doing something, makes me wonder if there's reason don't understand.
see example below. purpose of example create 2 images change image source every time click them. question pertains use of indexof search single string (not array) - seems weird.
<!doctype html> <html lang="en"> <head> <title>chapter 10: example 1</title> </head> <body> <img src="usa.gif" onclick="changeimg(this)" /> <img src="mexico.gif" onclick="changeimg(this)" /> <script> var myimages = [ "usa.gif", "canada.gif", "jamaica.gif", "mexico.gif" ]; function changeimg(that) { var newimgnumber = math.round(math.random() * 3); while (that.src.indexof(myimages[newimgnumber]) != -1) { newimgnumber = math.round(math.random() * 3); } that.src = myimages[newimgnumber]; } </script> </body> </html>
so, instead of using indexof, seems lot easier write like:
while (that.src == myimages[newimgnumber])) { newimgnumber = math.round(math.random() * 3); }
would work? seems lot easier understand, when reviewing code. or there reason way did it?
update: think know answer, after reflecting on few more minutes. i'm guessing src returned long string, not short string contained in myimages array. need use indexof discover whether string myimages found anywhere inside src that.src. right?
incidentally, method of creating random numbers bugs me - instead of:
newimgnumber = math.round(math.random() * 3);
i prefer:
newimgnumber = math.floor(math.random() * 4);
the first method won't create distribution between 4 elements of array. maybe figure round vs. floor distinction isn't worth going in book beginners.
the problem src
idl attribute return result of resolving relative url absolute one.
instead, can use getattribute
src
content attribute:
var img = document.images[0]; document.body.innerhtml = '' +'<dl>' +'<dt>src idl attribute:</dt>' +'<dd>' + img.src + '</dd>' +'<dt>src content attribute:</dt>' +'<dd>' + img.getattribute('src') + '</dd>' +'</dl>';
<img src="usa.gif" />
therefore, use this:
var myimages = [ "usa.gif", "canada.gif", "jamaica.gif", "mexico.gif" ]; var els = document.getelementsbyclassname('myclass'); for(var i=0; i<els.length; ++i) els[i].addeventlistener('click', changeimg); function changeimg() { var newimgnumber; { newimgnumber = math.floor(math.random() * myimages.length); } while (this.getattribute('src') == myimages[newimgnumber]); this.src = myimages[newimgnumber]; }
<img src="usa.gif" class="myclass" /> <img src="mexico.gif" class="myclass" />
Comments
Post a Comment