简体   繁体   English

如何从外部js文件中呈现html

[英]How to render html from a external js file

This might be a dumb question but I have actually never done this and what I am trying is not working. 这可能是一个愚蠢的问题,但我实际上从来没有这样做,我正在尝试的是不起作用。

I have 2 files 我有2个文件

test.html
test.js

I am linking the js as an external in test.html 我将js作为外部链接在test.html中

<!doctype html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>

<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
</body>
</html>

In my js file I have something like this 在我的js文件中,我有类似的东西

document.appendChild('<div>testing</div>')

I also tried 我也试过了

document.getElementsByTagName('body').appendChild('<div>testing</div>')

What I am doing wrong? 我做错了什么? I just want to learn how to generate html from an external js file for a future project I am working on. 我只想学习如何从外部js文件生成html,以用于我正在进行的未来项目。

You should generally try to run scripts that depend on the page after the document has been parsed, not before - if you put the script in <head> and run it immediately, the <body> has not been created yet. 您通常应该在解析文档尝试运行依赖于页面的脚本,而不是之前 - 如果您将脚本放在<head>并立即运行,则尚未创建<body> Give your script tag the defer attribute so that it only runs after the document is fully parsed: 为脚本标记提供defer属性,以便它仅在文档完全解析后运行:

<script defer type="text/javascript" src="test.js"></script>
  • appendChild accepts an element as a parameter, not a string appendChild接受一个元素作为参数,而不是字符串

  • You need to append to the body , not the document itself ( Only one element on document allowed. ) 您需要附加到body ,而不是document本身( Only one element on document allowed.

  • If you want to append an HTML string, assign/concatenate to the .innerHTML property 如果要附加HTML字符串,请指定/连接到.innerHTML属性

  • Assigning to .innerHTML will corrupt existing references to elements inside, including listeners. 分配给.innerHTML将破坏对内部元素的现有引用,包括侦听器。 In order to keep listeners active, use insertAdjacentHTML instead: 为了使侦听器保持活动状态,请使用insertAdjacentHTML

 document.body.appendChild(document.createElement('div')) .textContent = 'testing1'; // Another method: document.body.innerHTML += '<div>testing2</div>'; // Another method: document.body.insertAdjacentHTML('beforeend', '<div>testing3</div>'); 

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

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