spires Posted November 6, 2007 Share Posted November 6, 2007 Hi Guys. I'm new to javascript. I'm trying to get an if statment to display different images. <script type="text/javascript"> if (id==link1) { document.write("<a href="#" id="link1"><img src="page GFX/New_Products/More_offers.jpg"></a>") } else { document.write("<a href="#" id="link2"><img src="page GFX/New_Products/Back_to_start.jpg"></a>") } </script> Can someone let me know where i'm going wrong. Thanks for your help Quote Link to comment Share on other sites More sharing options...
fenway Posted November 6, 2007 Share Posted November 6, 2007 A few things... 1) link1 is a string, not a JS variable. Not that I know where the id variable comes from...? 2) You have quoting issues -- you can't put double quotes in a double quoted string literal, or the parser won't know where the string starts and end. 3) document.write() isn't always the best way to go. 4) You have lots of code duplication -- a hash would be better. 5) No semi-colons? 6) No functions? Something like: <script type="text/javascript"> var sLink = ( hLinks[id] ) ? id : 'DEFAULT'; var hLinks = { 'link1':{ 'id':'link1', 'href':'#', 'src':'page GFX/New_Products/More_offers.jpg' }, 'link2':{ 'id':'link2', 'href':'#', 'src':'page GFX/New_Products/Back_to_start.jpg' }, 'DEFAULT':{ 'id':'default, 'href':'#', 'src':'page GFX/New_Products/default.jpg' } }; var sImageHTML = '<a href="'+hLinks[sLink].href+'" id="'+hLinks[sLink].id+'"><img src="'+hLinks[sLink].src+'"></a>'; document.write( sImageHTML ); </script> Of course, if I were emehrkay, then writing out the HTML code would be method of an custom object ;-) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.