css必须只应用一个座位<li>(限制多个选择)</li>

时间:2014-03-31 07:07:14

标签: javascript jquery

巴士预订

以下代码生成multilpe <li>,当用户点击座位时,所选座位css将会更改。但我想限制多项选择。用户必须只允许选择一个座位,如果他选择第二个<li>(座位),则第一个座位必须取消选择

DEMO:http://demo.techbrij.com/780/seat-reservation-jquery-demo.php

代码:http://techbrij.com/seat-reservation-with-jquery

    $(function () {
        var settings = {
            rows: 6,
            cols: 6,
            rowCssPrefix: 'row-',
            colCssPrefix: 'col-',
            seatWidth: 30,
            seatHeight: 30,
            seatCss: 'seat',
            selectedSeatCss: 'selectedSeat',
            selectingSeatCss: 'selectingSeat'
        };

        var init = function (reservedSeat) {
            var str = [], seatNo, className;
            for (i = 0; i < settings.rows; i++) {
                for (j = 0; j < settings.cols; j++) {

                    seatNo = (i + j * settings.rows + 1);   // Seat No  eg : seatNo = 0+0*0+1 (1)
                    className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString(); // Class each seat class Name=seat row-0 col-0

                    if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
                        className += ' ' + settings.selectedSeatCss;
                    }

                    str.push('<li onclick="gettable('+ seatNo+')" class="' + className  +" table"+seatNo+ '">' 

                                +'<a title="' + seatNo + '">' + seatNo + '</a>' +
                              '</li>');
                }
            }
            $('#place').html(str.join(''));
        };




        var bookedSeats = [5, 10, 25];
        init(bookedSeats);


        $('.' + settings.seatCss).click(function () {
        if ($(this).hasClass(settings.selectedSeatCss)){
            alert('This seat is already reserved');
        }
        else{
            $(this).toggleClass(settings.selectingSeatCss);


            }
        });

3 个答案:

答案 0 :(得分:0)

首先从所有元素中删除该类,然后将其添加到所选元素中。

$('.' + settings.seatCss).click(function () {
        if ($(this).hasClass(settings.selectedSeatCss)){
            alert('This seat is already reserved');
        }
        else{
            $('.' + settings.seatCss).removeClass(settings.selectingSeatCss);
            $(this).addClass(settings.selectingSeatCss);


            }
        });

答案 1 :(得分:0)

将else部分更改为:

 else{
      $(this).toggleClass(settings.selectingSeatCss);
      $(".settings.selectingSeatCss").not(this).removeClass('settings.selectingSeatCss');
      }

答案 2 :(得分:0)

尝试使用此代码更改click()事件中的代码。

$('.' + settings.seatCss).click(function () {
   $(this).addClass(settings.selectedSeatCss).siblings(this).removeClass(settings.selectedSeatCss);
});

工作Demo。希望它可以帮到你。