如何用js动态写入html代码?

html-css08

如何用js动态写入html代码?,第1张

所谓动态写入方法就是源文件代码中原来没有内容或者需要重新改变此处的要显示的文字或内容,需要用JavaScript代码来实现。动态写入是一种很常见常用的方法。\x0d\x0a1、用innerHTML写入html代码:\x0d\x0a\x0d\x0adocument.getElementById("abc").innerHTML="要写入的文字或内容"\x0d\x0a2、appendChild() 方法:\x0d\x0aCoffeeTea\x0d\x0a点击向列表添加项目\x0d\x0a\x0d\x0afunction myFunction(){\x0d\x0avar node=document.createElement("LI")\x0d\x0avar textnode=document.createTextNode("Water")\x0d\x0anode.appendChild(textnode)\x0d\x0adocument.getElementById("myList").appendChild(node)\x0d\x0a}\x0d\x0a 回答于 2022-12-14

一、使用javascript 模板引擎

用javascript预编译模版,就是动态修改模板文件使之成为一个可用的静态HTML文件。 我平时会使用artTemplate,性能很好而且易上手。

编写模板

使用一个type="text/html"的script标签存放模板:

<script id="test" type="text/html">

<h1>{{title}}</h1>

<ul>

{{each list as value i}}

<li>索引 {{i + 1}} :{{value}}</li>

{{/each}}

</ul>

</script>

渲染模板

var data = {

title: '标签',

list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']

}

var html = template('test', data)

document.getElementById('content').innerHTML = html

二、使用CoffeeScript

CoffeeScript支持类似于Python的跨行字符串,这样很轻易的就能保持HTML结构的可读性,而不需要使用“+”或者采用拼数组的形式。

str="""

<div class="dialog">

<div class="title">

<img src="close.gif" alt="关闭" />关闭

</div>

<div class="content">

<img src="delete.jpg" alt="" />

</div>

<div class="bottom">

<input id="Button2" type="button" value="确定" class="btn"/>

<input id="Button3" type="button" value="取消" class="btn"/>

</div>

</div>

"""

js在特定位置动态添加html可以利用HTML DOM appendChild() 方法。例子:var div1 = document.createElement("div")div1.id = "div1"var div2 = document.createElement("div")div2.id ="div2"document.body.appendChild(div1)div1.appendChild(div2)appendChild()定义和用法:appendChild() 方法向节点添加最后一个子节点。提示:如果您需要创建包含文本的新段落,请记得添加到段落的文本的文本节点,然后向文档添加该段落。您也可以使用 appendChild() 方法从一个元素向另一个元素中移动元素。从一个列表向另一个列表中移动列表项:var node=document.getElementById("myList2").lastChilddocument.getElementById("myList1").appendChild(node)