jquery problem- function repeats
I have two thumbnails in <a>
tag by clicking them another image (main image) src
will change to <a> hrefs
tag to show fullsize image.
The function works, but problem is that when I track the function It will repeat relatively to number of clicks.
If its 1st click it runs once, if its 2nd click it runs twi开发者_JAVA技巧ce and so on. Here is my code:
<div class="wraptocenter"><img alt="" src="" id="myim" /></div>
<a href="images/cam1.jpg" class="changemimg"> <img alt="" src="images/10.jpg" /></a>
<a href="images/cam.jpg" class="changemimg" ><img alt="" src="images/9.jpg" /></a>
<img src="" id="hiddenimg" style="display:none" />
$(document).ready(function () {
$(".changemimg").bind('click', set);
function set() {
$("#myim").attr("src", "images/indicators.gif");
var path = $(this).attr("href")
$("#hiddenimg").attr("src", path);
$("#hiddenimg").load(function () { alert('hi'); $("#myim").attr("src", path); });
return false;
}
});
Thanks in advance for any suggestions!
Your Load event handler on the "hiddenimg" element is set everytime the anchor element is clicked. So after each click the number of Load event handlers are increasing by one. Following code should resolve your issue
$(document).ready(function () {
var path;
$(".changemimg").bind('click', set);
$("#hiddenimg").load(function () {
alert('hi');
$("#myim").attr("src", path);
});
function set() {
$("#myim").attr("src", "images/Calendaricon.gif");
path = $(this).attr("href");
$("#hiddenimg").attr("src", path);
$("#hiddenimg").attr("style", "display:block");
return false;
}
});
Try:
$(document).ready(function () {
$(".changemimg").bind('click', set);
function set(e) {
e.preventDefault();
$("#myim").attr("src", "images/indicators.gif");
var path = $(this).attr("href");
var myimg = new Image();
$(myimg)
.load(function(){
alert('hi');
$('#myim').attr('src', path);
})
.attr('src', path);
}
});
Here is a demo
精彩评论