如何用js动态写入html代码

如题所述

var div = document.createElement("div");
div.id = "myDiv";
div.innerHTML = "你要填入的html代码";
document.body.appendChild(div);
//jquery 版本
$("#id").html("你要填入的html代码");
//总之动态写入html代码是挺灵活的,还有什么类似document.write();等等。希望能够帮到你。
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-12-04
所谓动态写入方法就是源文件代码中原来没有内容或者需要重新改变此处的要显示的文字或内容,需要用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>
相似回答