简体   繁体   English

将图像添加到 <div> 使用jQuery

[英]Adding images into a <div> using jQuery

This is a "Crystals Collector" game which creates four crystals ("divs") with random numbers inside them, which the user clicks to add numbers to a random number the computer has generated, to match the computer's random number. 这是一个“水晶收集器”游戏,它创建了四个带有随机数字的晶体(“div”),用户点击这些数字将数字添加到计算机生成的随机数,以匹配计算机的随机数。 Everything works but I'm having a hard time adding the images of crystals I need into the 4 divs. 一切正常但我很难将所需的水晶图像添加到4个div中。

var image = "../../assets/images/crystal.jpg"

var crystal = $("<div>");
crystal.attr({
    "class": 'crystal',
    "data-random": randomNum,
    "src": image
});
$(".crystals").append(crystal);

The only result I need is for 4 crystal images to show in my 4 divs created for the random number clicks. 我需要的唯一结果是4个水晶图像显示在为随机数点击创建的4个div中。

Instead of div create img tag. 而不是div创建img标签。

 var image = "https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg" var crystal = $("<img>"); crystal.attr({ "class": 'crystal', "data-random": 1, "src": image, "height": '100px', "width": '100px' }); $(".crystals").append(crystal); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="crystals"></div> 

Create the image and add to div 创建图像并添加到div

 var elem = document.createElement("img"); elem.setAttribute("src", "images/hydrangeas.jpg"); elem.setAttribute("height", "768"); elem.setAttribute("width", "1024"); elem.setAttribute("alt", "Flower"); document.getElementById("placehere").appendChild(elem); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM