至少对于我来说有点棘手。这是场景:
<div id="gifs">
<img src="gif/1.jpg" alt="" >
<img src="gif/10.jpg" alt="" >
<img src="gif/15.jpg" alt="" >
<img src="gif/20.jpg" alt="" >
<img src="gif/5.jpg" alt="" >
</div>
每次用户单击图像时,图像都会变为gif,并且ID带有时间戳。
问题是,我一次不想超过4个gif。这意味着,如果有4个gif,则用户下次单击时,较旧的将返回为jpg。我怎样才能做到这一点?
到目前为止,这是我的jquery:
$("#gifs img").click(function () {
var original = $(this).attr("src");
var newsrc = original.replace('jpg','gif');
if(!$(this).hasClass('on')){
$(this).attr("src" , '');
$(this).attr("src", newsrc );
$(this).addClass('on');
var t = new Date();
var time = t.getTime();
$(this).attr('id' , time);
// HELP MOSTLY HERE, IN THE EACH FUNCTION. NEED TO STORE TIMESTAMP INSIDE AN ARRAY...
$('.on').each(function(e){
//dif[] = $(e).attr('id');
});
/*var oldest = dif.min();
var oldestsrc = $('#'+oldest).attr("src");
var oldestnewsrc = oldestsrc.replace('gif','jpg');
$('#'+oldest).attr("src",oldestnewsrc); */
}
});
帮助非常感谢。
最佳答案
我会这样做:
(function () {
// cache images so that we can use them later
var $imgs = $("#gifs img");
$imgs.click(function () {
var $this = $(this);
if (!$this.hasClass("on")) {
// get all IDs of those images that are "on"
var ids = Array.prototype.slice.call($imgs.filter(".on").map(function () { return this.id; }));
if (ids.length >= 3) {
// get oldest image by sorting the IDs in ascending order and get the first
var $oldest = $("#"+ids.sort()[0]);
// change oldest image
$oldest.attr("src", function () { return this.src.replace("gif", "jpg"); });
$oldest.removeClass("on");
}
// change for clicked image
$this.attr("id", new Date().getTime());
$this.attr("src", function () { return this.src.replace("jpg", "gif"); });
$this.addClass("on");
}
});
})();
整体包装在一个函数中,以免污染全局变量范围。