有没有办法把它变成for循环?我必须运行此代码114次,我正在寻找一种方法来简化这一点。类名称上的数字将是变量。下一个是.select3等......
$('.select2').click(function () {
if ($('.saved_list .thumb2').length == 0 && $('.saved > li').length < totalPic)
{
$(this).parent().clone().appendTo('.saved_list ul');
$('.saved .select2').replaceWith('<div class="remove2">Remove</div>');
$('.saved a').contents().unwrap();
} else {
alert ('You can only choose 3 paintings');
}
if ($('.saved_list li').has('.thumb2')) {
$(".select2 .img-swap").attr("src", "images/check_on.gif");
} else {
$(".select2 .img-swap").attr("src", "images/check_off.gif");
};
});
答案 0 :(得分:2)
试试这个:
var run_select = function(index){
var selector = '.select'+index;
$(selector).click(function () {
if ($('.saved_list .thumb2').length == 0 && $('.saved > li').length < totalPic)
{
$(this).parent().clone().appendTo('.saved_list ul');
$('.saved '+selector).replaceWith('<div class="remove2">Remove</div>');
$('.saved a').contents().unwrap();
} else {
alert ('You can only choose 3 paintings');
}
if ($('.saved_list li').has('.thumb2')) {
$(selector+" .img-swap").attr("src", "images/check_on.gif");
} else {
$(selector+" .img-swap").attr("src", "images/check_off.gif");
};
});
};
var i, l = 114;
for(i=1;i<=114;i++){
run_select(i);
}
答案 1 :(得分:-1)
首先,如果可以的话,简化html。使用id作为唯一标识符,并为css类使用相同的名称。像这样:
<div id='select2' class='select'></div>
如果您想获得所有物品,请使用.each()
:
$('.select').each(function() {
// use $(this) here to refer to the current item
});
但在您的情况下,您可以简单地应用“点击”事件:
$('.select').click(function(e) {
// use $(this) or $(e.target) here to refer to the current item
// if you need to get the id number you could get it from the id
// (supposing has id='select2')
var id = $(this).attr('id').substring(6); // it returns 2
});