[英]Image Display using Javascript OOP
我想從<button>
顯示圖像,但是似乎存在某種問題。
我無法顯示圖像。 我讀過一些有關Javascript和OOP的文章,只是不知道我是否正確使用了它們。
現在轉到我的代碼,如下所示:
function myFunction() {
function Image(src, height, width) {
this.src = src;
this.height = height;
this.width = width;
}
image.prototype.display = function () {
document.body.appendChild(image);
}
var image = new Image("image.jpg", "200", "200");
image.display();
}
}
希望你能幫助我:)
您需要創建一個DOM元素並向其中添加屬性。 這是jsfiddle上的一個工作示例:
function myFunction() {
function Image (src, height, width) {
this.src = src;
this.height = height;
this.width = width;
}
Image.prototype.display = function() {
var img = document.createElement('img');
img.setAttribute("src", this.src);
img.setAttribute("height", this.height);
img.setAttribute("width", this.width);
document.body.appendChild(img);
}
var image = new Image ( "http://www.zwani.com/graphics/hello/images/10.gif", "200" , "200" );
image.display();
}
myFunction();
似乎在定義自己的Image
類時,似乎沒有提供任何值得DOM渲染的東西。
您的display
方法可能看起來更像(注意Image
的大寫):
Image.prototype.display = function() {
// probably actually want to put this in the constructor
// i.e., one img element per Image object
var image = document.createElement("img");
image.src = this.src;
image.style.height = this.height;
image.style.width = this.width;
// also probably don't want to append to body every time
// display is called, style.display = "inline" or similar
// would be better with a corresponding hide method
document.body.appendChild(image);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.