JavaScript生成新标签的三个方法(摘抄自留)
1 <div ></div> 2 <script> 3 //HTML 4 function a(){ 5 document.getElementById("d1").innerHTML="<img src='http://baike.baidu.com/cms/rc/240x112dierzhou.jpg'>"; 6 } 7 a(); 8 //方法 9 function b(){ 10 var d1=document.getElementById("d1"); 11 var img=document.createElement("img"); 12 img.src="http://baike.baidu.com/cms/rc/240x112dierzhou.jpg"; 13 d1.appendChild(img); 14 } 15 b(); 16 //对象 17 function c(){ 18 var cc=new Image(); 19 cc.src="http://baike.baidu.com/cms/rc/240x112dierzhou.jpg"; 20 document.getElementById("d1").appendChild(cc); 21 pload(); 22 } 23 c(); 24 </script>
使用JavaScript或者jQuery的方法相对灵活一些
1 <script src="http://code.jquery.com/jquery-1.4.1.min.js"></script> 2 <script type='text/javascript'> 3 $('.hello').html("<img src='http://baike.baidu.com/cms/rc/240x112dierzhou.jpg'></img>"); // 覆盖原来标签的内容 4 $('.hello').append("<img src='http://baike.baidu.com/cms/rc/240x112dierzhou.jpg'></img>"); // 追加(标签内) 5 $('.hello').after("<img src='http://baike.baidu.com/cms/rc/240x112dierzhou.jpg'></img>"); // 追加(标签外)后 6 </script>
预留动态加入形式的js代码:
1 $(function(){ 2 $(".add_station").click(function(){ 3 $(this).after('<p class="add_station">就是你</p>'); 4 }); 5 }); 6 // 新生成的元素,没有单击触发事件(原来的有,新生成的没有) 7 8 $(function(){ 9 $(".add_station").live('click' , function(){ 10 $(this).after('<p class="add_station">就是你</p>'); 11 }); 12 }); // 这个代码可以解决这个问题
原文链接:https://www.cnblogs.com/online-link/p/6062423.html
本文来源 爱码网,其版权均为 原网址 所有 与本站无关,文章内容系作者个人观点,不代表 本站 对观点赞同或支持。如需转载,请注明文章来源。
© 版权声明
文章版权归作者所有,未经允许请勿转载。