我使用 Google Weather API 制作了一个插件,目前正在从 Google 的 API 中提取图像。对于一个阳光明媚的日子,我正在拉http://www.google.com//ig/images/weather/sunny.gif
。
我正在寻找一种方法,以便在拉取sunny.gif 时,用我选择的图像替换。
jQuery或其他方式有可能吗?
非常感谢
我使用 Google Weather API 制作了一个插件,目前正在从 Google 的 API 中提取图像。对于一个阳光明媚的日子,我正在拉http://www.google.com//ig/images/weather/sunny.gif
。
我正在寻找一种方法,以便在拉取sunny.gif 时,用我选择的图像替换。
jQuery或其他方式有可能吗?
非常感谢
$("#my_image").attr("src","http://www.myimagepath.com/image.jpg");
取决于您如何接收/传递图像,只需将其设置为变量并检查它。这是这个简单问题的简单/懒惰的解决方案,如果您的问题更复杂,您可以将其转换为检查和替换阳光、暴风雨等的功能......
if (img === "http://www.google.com//ig/images/weather/sunny.gif") {
img = "myownimage.gif";
}
PHP/JS 反模式:
<?php if ($image === "http://www.google.com//ig/images/weather/sunny.gif"): ?>
<script type="text/javascript">
$("#image").attr('src', 'foo.gif');
</script>
<?php endif; ?>
但老实说,如果您使用 PHP 接收图像,那么我只需在服务器端对其进行操作并将其显示给客户端,而不是让 JavaScript 来执行...
<?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" />
文档中有一个包含所有 img 元素的 live document.images集合。您可以根据您喜欢的任何逻辑有条件地更改任何特定图像的 src 属性:
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';
}
您可能还想访问图像的parentNode及其一些属性。
但在我看来,这在服务器上做得更好。