JavaScript生成新标签的三个方法(摘抄自留)

 1     <div id="d1"></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 }); // 这个代码可以解决这个问题

 

posted @ 2016-11-14 16:45  凌晨两点一刻  阅读(1505)  评论(0编辑  收藏  举报