现在的位置: 网页制作教程JS网页特效 >正文
JavaScript脚本

insertAdjacentHTML动态插入内容的使用方法

发表于2016/10/25 JS网页特效 0条评论 ⁄ 热度 2,936℃

添加HTML内容与文本内容以前用的是innerHTML与innerText方法,最近发现还有insertAdjacentHTML和insertAdjacentText方法,这两个方法更灵活,可以在指定的地方插入html内容和文本内容。

insertAdjacentHTML方法:在指定的地方插入html标签语句

insertAdajcentHTML的语法

insertAdajcentHTML(swhere,stext)

insertAdjacentHTML参数:

swhere: 指定插入html标签语句的地方,有四种值可用:

1.beforeBegin: 插入到标签开始前

2.afterBegin:插入到标签开始标记之后

3.beforeEnd:插入到标签结束标记前

4.afterEnd:插入到标签结束标记后

stext:要插入的内容

insertAdjacentHTML代码实例:

insertAdjacentHTML动态插入内容

实例一

<html>
 <head>
  <script language="javascript">
   function myfun(){
    var obj = document.getElementById("btn1");
    obj.insertAdjacentHTML("afterEnd","<br><input name="txt1">");
   }
  </script>
 </head>
 <body>
   <input name="txt">
   <input id="btn1" name="btn1" type="button" value="更多" onclick="myfun()">
 </body>
</html>

实例二

<html>
 <head>
  <title>24.htm insertAdjacentHTML插入新内容</title>
   <script language="jscript">
    function addsome()
    {
     document.all.paral.insertAdjacentHTML("afterBegin","<h1>在文本前容器内插入内容</h1>");
     document.all.paral.insertAdjacentHTML("beforeEnd","<h2>在文本后容器内插入内容</h2>");
     document.all.paral.insertAdjacentHTML("beforeBegin","<h4>在文本前容器外插入内容</h1>");
     document.all.paral.insertAdjacentHTML("afterEnd","<h5>在文本后容器外插入内容</h2>");
    }
   </script>
  </head>
  <body onload="addsome()">
   <div id="paral" style="fontsize:6;color='#ff00ff'">原来的内容</div><hr>
  </body>
</html> 

实例二

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
 </HEAD>
 <BODY>
  <script>
   var num=0;
   var No_sys=0;
   function Add_button(){
    if(No_sys<8){
     c_input.insertAdjacentHTML("beforeEnd","<div id="bar"+num+"" oncontextmenu="Remove_button(bar"+num+");return    false" style="background:red;width:40;height:20">"+num+"</div>");
     num++;
     No_sys++;
    }
   }
   function Remove_button(obj){
     obj.removeNode(true);
     No_sys--;
   }
 </script>
 <input type="button" onclick="Add_button()" value="动态加">
 <input type="button" onclick="alert(c_input.innerHTML)" value="看">
 <div id="c_input">
 </div>  
 </BODY>
</HTML>

好了,关于insertAdjacentHTML的使用方法就介绍到这里,希望对你有用。

推荐源码:旅行社整站源代码仪表公司源码

  • 暂无评论