Javascripts innerHTML not working for images, but works with text?

為{幸葍}努か 提交于 2020-01-11 10:52:32

问题


Ok, i have a javascript function which toggles the innerhtml of a div tag when a user changes the option of a select dropdown box..

It all works fine with text, but with an image tag it stops working?

Working Example...

function toggle(opt) {
        var d = document.getElementById('div_tag');
        if (opt == '5') {
                d.innerHTML = 'FIVE';
        }
        else if (opt == '4') {
                d.innerHTML = 'FOUR';
        }
        etc...
}

Not Working Example...

function toggle(opt) {
        var d = document.getElementById('div_tag');
        if (opt == '5') {
                d.innerHTML = '<img src='path/img1.jpg'><img src='path/img2.jpg'>';
        }
        else if (opt == '4') {
                d.innerHTML = '<img src='path/img2.jpg'><img src='path/img1.jpg'>';
        }
        etc...
}

This is what i have on my select and div tags.

<select onchange='toggle(this.value);'>
<div id='div_tag'></div>

Anyone tell me what i'm doing wrong here cos i am stumped.. why would one work and not the other when all that is different is one been the other being text??

Thanks.


回答1:


It seems to me like you forgot to escape the quotes surrounding your image paths, and its not reading your string correctly, try this

function toggle(opt) {
    var d = document.getElementById('div_tag');
    if (opt == '5') {
            d.innerHTML = '<img src=\'path/img1.jpg\'><img src=\'path/img2.jpg\'>';
    }
etc...



回答2:


Do these changes, replace ' with " at the beginning and end.

function toggle(opt) {
        var d = document.getElementById('div_tag');
        if (opt == '5') {
                d.innerHTML = "<img src='path/img1.jpg'><img src='path/img2.jpg'>";
        }
        else if (opt == '4') {
                d.innerHTML = "<img src='path/img2.jpg'><img src='path/img1.jpg'>";
        }
        etc...
}

You were actually using single quote instead of double quotes. path/img1.jpg, path/img2.jpg wasn't being treated part of your string earlier. That was the problem.

UPDATE For you php problem do this:

function toggle(opt) {
        var d = document.getElementById('div_tag');
        if (opt == '5') {
                d.innerHTML = '<img src='+'path/img1.jpg'+'><img src='+'path/img2.jpg'+'>';
        }
        else if (opt == '4') {
                d.innerHTML = '<img src='+'path/img2.jpg'+'><img src='+'path/img1.jpg'+'>';
        }
        etc...
}


来源:https://stackoverflow.com/questions/11266104/javascripts-innerhtml-not-working-for-images-but-works-with-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!