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

如何用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代码来实现。动态写入是一种很常见常用的方法。

1、用innerHTML写入html代码:

<div id="abc"></div>

<script>document.getElementById("abc").innerHTML="要写入的文字或内容"</script>

2、appendChild() 方法:

<ul id="myList"><li>Coffee</li><li>Tea</li></ul>

<button onclick="myFunction()">点击向列表添加项目</button>

<script>

function myFunction(){

var node=document.createElement("LI")

var textnode=document.createTextNode("Water")

node.appendChild(textnode)

document.getElementById("myList").appendChild(node)

}

</script>

一、使用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>

"""


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11652136.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-17
下一篇2023-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存