Replace given <img> source
I made a plugin with Google Weather API and I am currently pulling the images 开发者_开发技巧from Google's API. For a sunny day I'm pulling http://www.google.com//ig/images/weather/sunny.gif
.
I am looking for a way so that when ever sunny.gif is pulled, replace with with an image of my choice.
Is that possible with jQuery or other way?
Thanks alot
$("#my_image").attr("src","http://www.myimagepath.com/image.jpg");
Depends on how you're receiving/passing the image, just set it to a variable and check for it. This is the easy/lazy solution to this simple problem, if your problem is more complex you could turn this into a function that checks and replaces sunny, stormy, etc...
if (img === "http://www.google.com//ig/images/weather/sunny.gif") {
img = "myownimage.gif";
}
PHP/JS anti-pattern:
<?php if ($image === "http://www.google.com//ig/images/weather/sunny.gif"): ?>
<script type="text/javascript">
$("#image").attr('src', 'foo.gif');
</script>
<?php endif; ?>
But honestly if you're receiving the image in PHP, then I'd just manipulate it server-side and display it to the client then rather than have JavaScript do it...
<?php
if ($image === "http://www.google.com//ig/images/weather/sunny.gif") {
$image = 'foo.gif';
}
?>
<img src="<?php echo $image ?>" alt="my sunny day image" />
There is a live document.images collection of all img elements in the document. You can conditionally change the src property of any particular image based on whatever logic you like:
var image, images = document.images;
for (var i=0, iLen=images.length; i<iLen; i++) {
image = images[i];
if (image.src == 'whatever') image.src = 'new value';
}
You may want to access the image's parentNode and some of its properties too.
But is seems to me that this is much better done on the server.
精彩评论