我正在制作一个rpg游戏。因此,我正在尝试创建一个for循环,该循环将为屏幕生成此按钮,到目前为止,
$(document).ready(function() {
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'assets/images/young_link.jpg';
//var test = "<img src= '../images/young_link.jpg'>";
//var young_hero = ["young_link","young_zelda","impa", "malon"];
var young_hero = ["young_link"];
//var hero_images = [test];
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<buttons>");
hero_btns.addClass("hero");
hero_btns.attr("data-hero" , young_hero[i]);
hero_btns.attr("data-image" , imgArray[i]);
hero_btns.text(imgArray[i]);
hero_btns.text(young_hero[i]);
$("#buttons").append(hero_btns);
}
});
问题在于它没有将图像放在按钮上。
最佳答案
为了向按钮添加图像,您不仅需要做data-image
的工作,还需要实际创建<img>
标记并将其提供为图像的来源。然后,您将需要使用css在按钮中正确排列图像。
我已经更新了您的代码,以将图像添加到第一个按钮。
$(document).ready(function() {
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT7o2tCpqvs_XRpvtHbuRe9KwkzydiVhWLJ6YVTkQcpkev09w0MBCgNu2w';
//var test = "<img src= '../images/young_link.jpg'>";
var young_hero = ["young_link","young_zelda","impa", "malon"];
//var young_hero = ["young_link"];
//var hero_images = [test];
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>"); // changed from <buttons>
hero_btns.addClass("hero");
hero_btns.attr("data-hero" , young_hero[i]);
//hero_btns.text(imgArray[i]);
hero_btns.text(young_hero[i]);
hero_btns.append(imgArray[i])
$("#buttons").append(hero_btns);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons">
</div>
关于javascript - 在JavaScript中,显示数组中的图片吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40161329/