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

后端 未结 2 1850
说谎
说谎 2020-12-21 06:49

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

相关标签:
2条回答
  • 2020-12-21 07:23

    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...
    
    0 讨论(0)
  • 2020-12-21 07:23

    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...
    }
    
    0 讨论(0)
提交回复
热议问题