简体   繁体   English

如何将javascript变量添加到HTML图像src标记

[英]How do I add a javascript variable to HTML image src tag

I know this answer is out here, but I have been unable to find it (or at least recognize it when I saw it!). 知道这个答案在这里,但我一直无法找到它(或者至少在我看到它时就认出来了!)。 I'm a relative noob to jquery, so bear with me please. 我是jquery的亲戚,所以请耐心等待。

Problem: 问题:

I have 20 images, named 1.png through 20.png . 我有20张图片,名为1.png20.png I would like a different image to display randomly each time a user clicks a button. 我想在每次用户点击按钮时随机显示不同的图像。

What's working: 什么工作:

My javascript code to generate the random number looks like this: 我生成随机数的javascript代码如下所示:

var randomImage = 1 + Math.floor(Math.random() * 20);

What's not... 什么不是......

What I'm trying to do is pass the result of that to my HTML document as the name of the image, so that is reads something like this: 我想要做的是将结果传递给我的HTML文档作为图像的名称,所以这是这样的:

 <img id="randImg" class="img_answer" src="randomImage.png">

I tried concatenating, but can't seem to figure this out. 我尝试连接,但似乎无法解决这个问题。 Do I need to create a function that affects the img ID or class? 我是否需要创建一个影响img ID或类的函数? Can anyone point me to the cleanest way to do this? 谁能指出我最干净的方法呢?

var randomImage = 1 + Math.floor(Math.random() * 20);    
var imgName = randomImage+".png";
$("#randImg").attr("src",imgName);

Demo: http://jsfiddle.net/a9Ltw/ 演示: http//jsfiddle.net/a9Ltw/

Spelling it out a bit to help teach: 拼写一下以帮助教导:

On your page you'd have something like this: 在您的页面上,您将拥有以下内容:

<img id=randomImage />

And probably in the head to hide the image until you've picked one to load, this: 并且可能在头部隐藏图像,直到你选择一个加载,这:

<style>
#randomImage {
    width: 400px; height: 200px; /* or whatever the dimensions are */
    visibility: hidden;
}
</style>

Then in your Javascript: 然后在你的Javascript中:

var ordinal = 1 + Math.floor(Math.random() * 20);
$('#randomImage').css('visibility', 'visible').attr('src', ordinal + '.png');

So the HTML lays out the img tag, and some early CSS sets its dimensions and hides it so there's no ugly broken image icon etc in some browsers - just a blank space. 所以HTML列出了img标签,一些早期的CSS设置它的尺寸并隐藏它,所以在某些浏览器中没有丑陋的破碎图像图标等 - 只是一个空白区域。

Then eventually the Javascript loads and runs, determining a random ordinal. 然后最终Javascript加载并运行,确定随机序数。 The second line of Javascript calls jquery to make the img visible and set its src attribute to the random image. 第二行Javascript调用jquery使img可见并将其src属性设置为随机图像。

$(document).ready(function() {
    var randomImage = 1 + Math.floor(Math.random() * 20),    
                img = randomImage + ".png";

    $("#randImg").attr("src", img);
});

只需将一些默认图像添加到img标签,以防止在用户禁用JavaScript时显示任何内容,然后在jQuery中使用$("#randImg").attr("src", randomImage + ".png");

var thesoruce = "http://localhost:8080/content/dam/admin/" + id ;

 g_fb.find('p').append('<img src= '+thesoruce +'  height="250px" width="600px">');

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

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