简体   繁体   中英

Check image src is valid when setting

I have a small piece of noddy code, when clicking an image the user can change the source. This is the function I use

function doStuff(objId){
        newVal = prompt("new Value")
        if(newVal==""){
            newVal = "blank"
        }
    document.getElementById(objId).src=newVal+".png"
}

Is there a way to check before setting the src if that is a valid filename at the same point as when I check if the user has not specified anything? I'd like to be able to protect the page so if the user types "banana" and there is no banana.png available that I just change it to the blank.png file.

I've found various methods for doing it on error but wasn't sure how to do it in this instance as none of those seem to trigger if the page is being updated dynamically.

Thanks!

modify the img tag to show the default image on error

<img onerror="this.src='images/default.jpg'"/>

now you can execute you function to change image dynamically

function doStuff(objId){
        newVal = prompt("new Value")
        if(newVal==""){
            newVal = "blank"
        }
    document.getElementById(objId).src=newVal+".png"
}

attached a snippet below which changes images dynamically, if not found load the default image

 var server = 'https://homepages.cae.wisc.edu/~ece533/images/'; function changeImage(option) { document.getElementById('test').src = server + option.value; } 
 <html> <body> <img width='150' height='150' id='test' src="http://www.yostra.com/images/team/you.png" onerror="this.src='http://www.yostra.com/images/team/you.png'" /> <br> <select onchange='changeImage(this)'> <option>--Choose--</option> <option value='airplane.png'>airplane.png</option> <option value='baboon.png'>baboon.png</option> <option value='abs'>ABC</option> <option value='arctichare.png'>arctichare.png</option> <option value=''>----</option> </select> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM