2010-04-29 48 views
17

Tôi đã thử một số mã DOM HTML từ một số trang web, nhưng nó không hoạt động. Nó không thêm gì cả. Có ai có một ví dụ làm việc về điều này?Thêm hình ảnh vào html bằng javascript

this.img = document.createElement("img"); 
this.img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png"; 
src = getElementById("gamediv"); 
src.appendChild(this.img) 

Nhưng nó không thêm bất kỳ thứ gì vào div. (gamediv) Tôi đã thử document.body là tốt, không có kết quả.

Xin cảm ơn trước.

Trả lời

36

Bạn cần phải sử dụng document.getElementById() phù hợp 3.

Nếu bạn cố gắng này ngay bây giờ trong Firebug console:

var img = document.createElement("img"); 
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png"; 

var src = document.getElementById("header"); 
src.appendChild(img); 

... bạn muốn có được điều này:

Adding images to the HTML with JavaScript http://img94.imageshack.us/img94/3769/googso2.png

+0

this.img = document.createElement ("img"); this.img.src = "img/eqp /" + this.apparel + "/" + this.facing + "_ idle.png"; src = document.getElementById ("gamediv"); src.appendChild (this.img); Đã thay đổi ngay bây giờ, nhưng nó vẫn không xuất hiện trong div gamediv. – Anonymous

+0

@klausbyskov: Cảm ơn bạn đã sửa lỗi đánh máy. –

+0

@Anonymous: Có thể là đường dẫn 'src' không chính xác? Bạn có thể thử một hình ảnh với một con đường tuyệt đối, mà bạn biết chắc chắn tồn tại? Chẳng hạn như: 'http: // www.google.com/intl/en_com/images/logo_plain.png' –

1

Hãy loại bỏ này báo cáo quá

var img = document.createElement("img"); 
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png"; 
src = document.getElementById("gamediv"); 
src.appendChild(this.img) 
+0

Tại sao? Nó đang ở trong một lớp học. – Anonymous

3

này hoạt động:

var img = document.createElement('img'); 
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png'; 
document.getElementById('gamediv').appendChild(img) 

Hoặc sử dụng jQuery:

$('<img/>') 
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png') 
.appendTo('#gamediv'); 
4

Với một ít nghiên cứu tôi thấy rằng javascript không biết rằng Đối tượng tài liệu tồn tại trừ khi đối tượng đã được tải trước mã kịch bản (Khi javascript đọc xuống một trang).

<head> 
    <script type="text/javascript"> 
     function insert(){ 
      var src = document.getElementById("gamediv"); 
      var img = document.createElement("img"); 
      img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png"; 
      src.appendChild(img); 
     } 
    </script> 
</head> 
<body> 
    <div id="gamediv"> 
     <script type="text/javascript"> 
      insert(); 
     </script> 
    </div> 
</body> 
3

hoặc bạn có thể chỉ

<script> 
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the the script)*\"') 
document.getElementById('pic') 
</script> 
<div id="pic"> 
</div> 
Các vấn đề liên quan