问题
I have such a page:
<script type="text/javascript">
$(function () {
$("#links a").mouseover(function () {
$("#flag").attr("src", "/Images/" + $(this).attr("id") + ".png");
});
});
</script>
<div>
<img id="flag" src="/Images/austria.png" alt="austria" />
</div>
<div id="links">
<a id="austria" href="#">austria</a>
<a id="brazil" href="#">brazil</a>
<a id="japan" href="#">japan</a>
</div>
Every thing work fine in different browser(FF10,Chrome,IE9). But when I monitor network in IE9 with "F12 developer tools", every time that mouse goes over a link, there is a aditional request for image. But in FF and Chrome, by checking with FireBug and Developer tools, for each image, there is just one requst and second time you go over a link, there is no request.
what is the problem with IE9 (or my code ;))?
Is there any other solutions for my problem to prevent from this problem?
(Actually I want something like Yahoo Hot news, that for every news image, its request just called once, even in IE9).
回答1:
You are not checking if you have already loaded the current image; therefore, it will reload it even though it is already there. Some of the browsers were probably using a cached version of the image and therefore did not go get it again.
$(function () {
$("#links a").mouseover(function () {
var $flag = $("#flag");
var newImage = "/Images/" + $(this).attr("id") + ".png";
if ($flag.attr("src").indexOf(newImage) == -1)
$flag.attr("src", newImage);
});
});
Edit:
From our conversation I wrote up the following, is it what you were referring too?
HTML:
<div class="flag">
<img id="flag" src="/Images/austria.png" alt="austria" />
</div>
<div id="links">
<a id="austria" href="#">austria</a>
<a id="brazil" href="#">brazil</a>
<a id="japan" href="#">japan</a>
</div>
Javascript:
$(function () {
$("#links a").mouseover(function () {
var $flag = $(".flag");;
var $flagImg = $("#flag");
var imageID = $(this).attr("id");
if ($flagImg.attr("src").indexOf(imageID) == -1)
$flag.html('<img id="flag" src="/Images/' + imageID + '.png" alt="' + imageID + '" />');
});
});
Live DEMO
来源:https://stackoverflow.com/questions/10600678/loading-image-with-jquery-additional-request-in-ie9