你可以尝试这样的事情:
http://jsfiddle.net/EpjYe/
$(document).ready(function () {
var all_images = $("#images").children(".image");
var cur_selected = all_images.filter(".image-selected");
checkNoneSelected(all_images, cur_selected);
$("#prev").on("click", function () {
var all_images = $("#images").children(".image");
var cur_selected = all_images.filter(".image-selected");
if (!checkNoneSelected(all_images, cur_selected)) {
cur_selected = moveImage(all_images, cur_selected, -1, 0);
$("#hidden1").val(cur_selected.prop("src"));
}
});
$("#next").on("click", function () {
var all_images = $("#images").children(".image");
var cur_selected = all_images.filter(".image-selected");
if (!checkNoneSelected(all_images, cur_selected)) {
cur_selected = moveImage(all_images, cur_selected, 1, all_images.length-1);
$("#hidden1").val(cur_selected.prop("src"));
}
});
});
function checkNoneSelected(all_images, cur_selected) {
if (cur_selected.length === 0) {
all_images.first().addClass("image-selected");
return true;
}
return false;
}
function moveImage(all_images, cur_selected, direction, end_pos) {
var cur_index = all_images.index(cur_selected);
if (cur_index !== end_pos) {
var new_index = cur_index + direction;
cur_selected.removeClass("image-selected");
cur_selected = $(all_images[new_index]);
cur_selected.addClass("image-selected");
}
return cur_selected;
}
当然,您必须使用一致id
和class
属性,因为我的只是一个示例。