0

Is it possible to use toggleclass on a button when a maximum amount of appended items is reached?

I want 6 appended divs/items to be the maximum. I've added a variable counter. So it increases when an item is appended and it decreases when the removebutton is clicked. The last step is to toggleclass the button (like a disabled button). So when the maximum amount is reached, the button toggleClass = red.

What I want:

On the sixth appended item, the button background changes to red and doesn't append anymore items (disabled). When the user removes one, the button toggles back to it's original state and the button fire the append event again. How can I integrate toggleClass in my code?

HTML

<div id="addbutton">ADD</div>
<div id="box"></div>

JS

var amount = 0;
var div = '<div>' +
    '<input type="text"/>' +
    '<input type="button" class="removebtn" value="delete"/>' +
    '</div>';

$('#addbutton').click(function () {
    amount++;
    if (amount < 6) {
        $('#box').append(div);
        //alert(amount);
    } else {
        $(this).toggleClass(".red");
    }
});


$('.removebtn').live('click', function () {
    $(this).parent().remove();
    amount--;
});

JSFIDDLE

4

1 回答 1

2

更新了小提琴以更好地工作。仅在您实际添加时才增加金额。否则如果人们继续点击添加,即使它是红色的,数量也会增加。

试试这个更新小提琴:http: //jsfiddle.net/V395Y/2/

基本上你使用 addClass 和 removeClass。我更新了 Jquery 和你的 CSS(重要部分)

$(this).addClass("red");
$('#addbutton').removeClass('red');
background: red !important;

由于您的按钮已经有一个类,因此 Red 类的 bgcolor 必须是 !important。这告诉 broswer,随着类 red 的出现,红色比黄色更重要。当您删除类时,ofc 仅保留黄色(默认)类,并且按钮恢复为黄色。

于 2013-08-26T11:27:46.237 回答