zoukankan      html  css  js  c++  java
  • js动态添加html标签和属性_手动插入meta、script、div、img等标签

    web网页是由 html标签一层层组成的,js也可以动态添加对应的标签,比如mate标签、script标签、div标签、img标签等,动态创建的方法基本都差不多,下面将简单介绍下如何实现

    一:手动添加mate标签

    function addMeta(name,content){//手动添加mate标签
    	let meta = document.createElement('meta');
        meta.content=content;
        meta.name=name;
        document.getElementsByTagName('head')[0].appendChild(meta);
    }
    

      

    二:手动添加script标签

    function addScript(src){//手动添加script标签
    	let script=document.createElement("script");
        script.type="text/JavaScript";
        script.src= src;
        document.getElementsByTagName('head')[0].appendChild(script);
    }
    

      

    三:动态添加元素div

    function adddiv(pid,html,attr){//动态添加元素div
    	 attr=attr || {};
        let parent = document.getElementById(pid);
        let div = document.createElement("div");//添加 div
    	 for(let i in attr){//设置 div属性
    	 	div.setAttribute(i,attr[i]);
    	 } 
        div.innerhtml = html;
        parent.appendChild(div);
    }
    addDiv("pid","<p>动态添加的div</p>",{"id":"newDiv"});//调用
    

      

    摄图网https://www.wode007.com/sites/73204.html VJ师网https://www.wode007.com/sites/73287.html

    四:动态添加元素img标签

    function addImg(pid,src,attr){//动态添加元素img标签
    	attr=attr || {};
       let parent = document.getElementById(pid);
       let img = document.createElement("img");//添加 div
       for(let i in attr){//设置 div属性
    	 	img.setAttribute(i,attr[i]);
    	}
       img.src = src;
       parent.appendChild(img);
    }
     
    

      

     
  • 相关阅读:
    FastJson中JSONObject用法
    复盘项目模板
    java Enum 类型
    Java List集合总结
    Spring boot 使用Slf4j 日志
    java.lang.reflect.UndeclaredThrowableException
    Intellij IDEA 中使用 Debug
    Java 13位时间戳转换日期格式
    Java 时间格式转换
    Spring boot 自定义注解
  • 原文地址:https://www.cnblogs.com/ypppt/p/13340422.html
Copyright © 2011-2022 走看看