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

JavaScript022

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

所谓动态写入方法就是源文件代码中原来没有内容或者需要重新改变此处的要显示的文字或内容,需要用

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>

动态写入html代码,主要就是append方法或其他插入方法。如:

var ele=document.createElement('div')//创建div对象

ele.innerHTML='我是测试内容'//在div对象中写入内容

document.body.appendChild(div)//把div放在body标签最后面

jQuery相对于要简单一些,如:

$(document.body).append('<div>我是测试内容</div>')