【发布时间】:2015-05-14 09:51:44
【问题描述】:
您好,我是一名学生,目前正在做一个 html 和 javascript 项目。 我最初来到这个站点是为了寻找一种方法来从另一个数组中引用的 javascript 数组中获取图像并将其显示在预定义的 html 表中。
不出所料,我从未找到该问题的确切答案,但设法使用从各种帖子和回答所述帖子的用户提供的零碎代码和知识以自己的方式找到解决方案。
现在它可以工作了,我想问问大家是否可以帮助我简化代码,或者您是否可以建议将来更简单的替代方法。
我是 javascript 和 html 的新手。我正在使用 Firefox,但我还没有使用 jquery。
这是来自相关 html 页面的代码。
<body>
<table border="4px">
<caption>
Pet Table
</caption>
<tr>
<!-- Images-->
<td>
<script>
display(bat)
</script>;
</td>
<td>
<script>
display(goat)
</script>
</td>
<td>
<script>
display(butterfly)
</script>
</td>
</tr>
</table>
</body>
这是带有三个示例的 javascript。
function pet(species, name, colour, size, food, limb, img) {
this.species = species; //property of a pet
this.name = name; //property of a pet
this.colour = colour; //property of a pet
this.size = size; //property of a pet
this.food = food; //property of a pet
this.limb = limb; //property of a pet
this.img = img; //property of a pet
this.move = move; //a function of a pet defined to the pet
}
//array for images used in the pet array
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "resources/bat.gif";
imgArray[0].height = "200";
imgArray[0].width = "200";
imgArray[1] = new Image();
imgArray[1].src = "resources/goatVec01.png";
imgArray[1].height = "200";
imgArray[1].width = "200";
imgArray[2] = new Image();
imgArray[2].src = "resources/butterfly.gif";
imgArray[2].height = "200";
imgArray[2].width = "200";
<!-- more images -->
//adding variables to the pet array
var bat = new pet("fruit bat", "bats", "grey", "small", "apples", "wings", "0", move);
var goat = new pet("goat", "bastard", "off white", "goat-sized", "clothing", "hooves", "1", move);
var butterfly = new pet("butterfly", "flutterby", "rainbow", "petite", "nectar", "wings", "2", move);
<!-- more variables -->
//function used to call and display the images
function display(pet) {
var i = document.write(imgArray[pet.img].outerHTML);
}
如果我问第二个问题。自从我开始使用 Firefox 以来,我不得不使用这段代码来让 html 正常工作,但我想知道除了将这些添加到每个页面之外,是否还有其他方法可以做到这一点。
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
有很大帮助的帖子列表
Image from an array HTML Javascript
How to display an image thats in an array? JavaScript
How to display image with javascript?
The character encoding of the HTML document was not declared
【问题讨论】:
标签: javascript html arrays