Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - Variable for img src=

I have a question. Firstly, I am not going to pretend that I know what I am talking about here. I am a newbie to http and JavaScript.

I think my question may be answered in this post IMG SRC tags and JavaScript but I thought I would explain the exact thing I am trying to achieve in case there is an easier way.

I have a webpage, I want to display an image on it. Only thing is, the image is coming from an automated system monitor, the image is automatically generated each day and placed in a new directory depending on date.

e.g. On April 4 = "http://host/partition/2009/apr/04/cpu.gif"
e.g. On April 5 = "http://host/partition/2009/apr/05/cpu.gif"

To facilitate this, I have created some basic JavaScript to give me the date in the format I need it. I have all that working. Now I just want to use that variable I created to show the image. I have the JavaScript code stored in a function called displaydate() If I do this <script language="JavaScript"> displaydate() </script> I see "http://host/partition/2009/apr/05/cpu.gif" and that is correct.

Now how do I display this on the site correctly?

 <a href="displaydate()"><img src="displaydate()" </a></td>    //This does not work. I am just adding it to show where I have been heading.

P.S. I have read a lot of pages on this and been trying a lot of things, but have had no luck so far. Any help, would be much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, that page probably does answer your question. Basically, you want this javascript:

<script type="text/javascript">
document.getElementById('image').src = "yourpicture.png";
</script>

Except you want to replace the "yourpicture.png" with the function you wrote to generate the correct path to the image on disk, so...

<script type="text/javascript">
document.getElementById('image').src = displaydate();
</script>

Of course, you might need to modify this a bit for your own uses, the getElementById will take as an argument whatever the id attribute of your < img > tag is. You probably want to execute the above javascript after your page has loaded, i.e.:

<html>
<head>
<script type="text/javascript">
function load()
{
document.getElementById('image').src = displaydate();
}

function displaydate()
{
//your displaydate() function here
}
</script>
</head>

<body onload="load()">

<img src="nothing.jpg" id="image" name="image"/>
</body>
</html> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...