简体   繁体   English

从外部JS文件调用HTML内容

[英]Calling HTML content from external JS file

I'm having an issue with what seems like a simple enough task. 我在一个看起来很简单的任务上遇到了问题。 I have a web page where I need to load in and remove div content as the user clicks buttons. 我有一个网页,需要在用户单击按钮时加载并删除div内容。 My code doesn't seem to work though. 我的代码似乎不起作用。

The html: 的HTML:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Main Page</title>
    <link rel="stylesheet" href="assets/css/stylemain.css"/>

    <script src="assets/js/introduction.js"></script>

</head>

<body>

    <div id="container">   
        <div id="content">
            <div id="slide1">
                <p>Here is the first trigger. It should look something like this</p>
                <p><input type="button" onclick="part2()" value="Click Me!" /></p>
            </div>        
        </div>

and the .js file: 和.js文件:

function part2() {
    document.write("<div id="slide2">
                    <p>Here is the second trigger. It should be to the left</p>
                    <p>next line goes here</p>
                    </div>")
    }

It's coming up with a syntax error on line 2 of the js file (the document.write line) but I can't figure out why. 它在js文件的第2行上出现了语法错误(document.write行),但是我不知道为什么。 I tried it both with and without quotations but to no avail. 我尝试使用带引号和不带引号,但均无济于事。 Any help would be appreciated. 任何帮助,将不胜感激。

You have to escape the quotes: 您必须转义引号:

function part2() {
    document.write("<div id=\"slide2\">\n<p>Here is the second trigger. It should be to the left</p>\n<p>next line goes here</p>\n</div>");
}

A slightly cleaner solution is to use a combination of single quotes and double quotes: 稍微干净一点的解决方案是结合使用单引号和双引号:

function part2() {
    document.write('\
      <div id="slide2">\
        <p>Here is the second trigger. It should be to the left</p>\
        <p>next line goes here</p>\
      </div>'
    );
}

Note that if you want to use a string broken into multiple lines you must add the '\\' in the end of each line to let JS parser know the string continues to the next line. 请注意,如果要使用分成多行的字符串,则必须在每行的末尾添加“ \\”,以使JS解析器知道该字符串继续到下一行。

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

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