如果数组为空或有项目,则显示隐藏元素

时间:2015-08-11 17:51:23

标签: jquery arrays switch-statement show

我试图获取一个按钮并显示或消失,具体取决于列表/购物篮是否为空或至少有一个项目。

FIDDLE http://jsfiddle.net/amesy/vtg6nnce/16/

HTML ...

<a href="#" class="send-order">Place your order</a>
<div class="form">
    <p>Form then appears somewhere</p>
</div>
<ul class="cbp-rfgrid biscuits clearfix">
    <li>
        <button type="button" data-biscuit="custardcream" class="biscuit custardcream">Custard Creams</button>
    </li>
    <li>
        <button type="button" data-biscuit="jammydodger" class="biscuit jammydodger">Jammy Dodger</button>
    </li>
    <li>
        <button type="button" data-biscuit="hobnob" class="biscuit hobnob">Hobnob</button>
    </li>
</ul>
<div class="barrel"></div>

...的jQuery

$(function () {
    $('.biscuit').click(function () {
        $(this).toggleClass("selected");
    });

});

var barrel_items = [];

$('[data-biscuit]').click(function () {
    var biscuit = $(this).data('biscuit');
    add_to_barrel(biscuit);
});

function add_to_barrel(item) {
    if ($.inArray(item, barrel_items) !== -1) {
        return;
    }
    var name = '';
    switch (item) {
        case 'custardcream':
            name = 'Custard Creams';
            break;
        case 'hobnob':
            name = 'Hobnob';
            break;
        case 'jammydodger':
            name = 'Jammy Dodgers';
            break;
    }
    $('.barrel').append('<div class="chosen">' + name + '</div>');
    barrel_items.push(item);
    $('.send-order').toggleClass("show");
}

$(function () {
    $('.send-order').click(function () {
        //$(".selection").attr('src',"img/"+bicsuit+".jpg");
        //$(".basket ul").append('<li><a href="#"><img src="img/biscuit.jpg" class="clearfix"><div><h3>remove</h3></div></a></li>');
        $('.form').toggleClass("show");
    });
});

1 个答案:

答案 0 :(得分:1)

修正了它,我将此$("#barrel").val(biscuit);更改为$("#barrel").val(barrel);