Javascript innerHTML无法用于图像,但可以用于文本吗? [英] Javascripts innerHTML not working for images, but works with text?

查看:133
本文介绍了Javascript innerHTML无法用于图像,但可以用于文本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我有一个javascript函数,当用户更改选择下拉框的选项时,该函数会切换div标签的innerhtml.

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?

工作示例...

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...
}

这就是我的select和div标签上的内容.

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??

谢谢.

推荐答案

在我看来,您好像忘记了转义图像路径周围的引号,并且它无法正确读取字符串,请尝试

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...

这篇关于Javascript innerHTML无法用于图像,但可以用于文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆