简体   繁体   English

JavaScript innerHTML替换图像的麻烦

[英]trouble with JavaScript innerHTML to image replacement

I am new to JavaScript and am doing a project for a class. 我是JavaScript新手,正在为一个类做项目。 I want to create an Easter egg somewhere on the page that when clicked changes the whole page code to a single image. 我想在页面上的某处创建一个复活节彩蛋,单击该按钮可以将整个页面代码更改为单个图像。 This is my code just to test out the concept: 这是我的代码,仅用于测试概念:

<div id = "all">
    <p>The button below changes the whole page.</p>

    <button type = "button" onclick = "changePage()">Click Here</button>
</div>

<script>
    function changePage()
    {
        document.getElementById("all").innerHTML = "<img src = "stop.jpg" />";
    }
</script>

The content isn't replaced by the image stop.jpg, however when I change the line to: 内容不会被图像stop.jpg代替,但是当我将行更改为:

document.getElementById("all").innerHTML = "<h1>Whatever</h1>";

The code changes to the simple heading with no problems. 代码将更改为简单标题,没有问题。 Any idea why? 知道为什么吗?

Didn't you notice that quotes are repeating? 您是否没有注意到重复的报价? You should wrap your img with another quotes: 您应该用另一个引号将img换行:

'<img src = "stop.jpg" />'

Or escape them 或者逃脱他们

"<img src = \"stop.jpg\" />"

The problem is with your quoting. 问题在于您的报价。 The double quotes around the stop.jpg URL are ending the string that begins with <img . stop.jpg URL周围的双引号以<img开头的字符串结尾。 You need to use single quotes or escape the quotes: 您需要使用单引号或转义引号:

document.getElementById("all").innerHTML = "<img src = 'stop.jpg' />";

document.getElementById("all").innerHTML = "<img src = \"stop.jpg\" />";

Didn't you get a syntax error in the Javascript console? 您没有在Javascript控制台中收到语法错误吗? Or notice the changed color in SO's syntax highlighting? 还是注意到SO语法突出显示中更改的颜色?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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