这是我当前 fiddle 的链接
JS--
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png') src = 'http://imageshack.us/a/img20/1651/fibz.png';
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') src = 'http://imageshack.us/a/img703/8236/l6hu.png';
$(this).attr('src', src);
}
});
我可以在点击时切换图片和另一张图片,反之亦然。这没关系,但我只想在已经选择绿色图像时限制切换。如果我从选择框中选择 3,那么我只能将白色图像切换为绿色图像 3 次,不超过 3 次。我还需要另一个场景的帮助 - 如果我从选择框中选择 3 并切换前 3 个图像,下一刻我改变第二张图片变成白色,点击第五张图片变成绿色就可以了。我在 javascript 或 jquery 上一周,所以需要有关此问题的适当信息。所以请帮助我。
最佳答案
这里有一个更全面的方法fiddle这将使您的限制保持同步并在限制更改时处理差异。
var quantity = 0; // will maintain limit
var stack = []; // will maintain ordered green buttons
$("#select").change(runWrapper);
function runWrapper() {
quantity = Number($("#select").val()); // set the limit
groom(); // turn off those that were turned on last
//run(); // this is your run function, uncomment
}
function groom(){
// let's test if we are over the limit
while(stack.length > quantity) {
// remove last which was set to green
$(stack.pop()).trigger("click")
// to remove the oldest/first set to green use
// $(stack.shift()).trigger("click")
}
}
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png') {
// limit reached
if(stack.length >= quantity) {
alert(quantity + " limit reached!");
return;
}
src = 'http://imageshack.us/a/img20/1651/fibz.png';
// turning green push the DOM reference to the top of the stack
stack.push(this);
}
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') {
src = 'http://imageshack.us/a/img703/8236/l6hu.png';
// turning white remove the DOM reference from stack
var self = this;
stack = $.grep(stack, function(val) {
return self != val;
})
console.warn(stack);
}
$(this).attr('src', src);
}
});
关于javascript - 根据选择框值限制javascript切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20669139/