从外部JS文件调用HTML内容

Calling HTML content from external JS file

本文关键字:HTML 内容 调用 文件 JS 从外部      更新时间:2023-09-26

我遇到了一个看似足够简单的任务的问题。我有一个网页,当用户单击按钮时,我需要在其中加载和删除div内容。不过,我的代码似乎不起作用。

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>

和.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>")
    }

它在js文件的第2行(document.write行)出现了语法错误,但我不知道为什么。我试过引用和不引用,但都没有用。如有任何帮助,我们将不胜感激。

您必须转义引号:

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>");
}

一个稍微干净一点的解决方案是使用单引号和双引号的组合:

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>'
    );
}

请注意,如果您想使用一个分为多行的字符串,则必须在每行的末尾添加"''",以使JS解析器知道该字符串将继续到下一行。