Jquery .on()事件在同一类元素上多次触发,即使使用.off()也是如此

时间:2015-02-28 13:58:05

标签: javascript jquery

我正在创建onthefly网格布局,其中一个类将附加到单击的类元素,并且输入字段中的一些手动文本将插入该元素中。

当我点击元素时,它被激活并且html被传递给该元素但是在点击第二个元素时,.on()会多次触发,所有元素都会获得相同的html数据而不是单独的数据。

我尝试过.off()和.stopPropagation()等。 enter image description here

function changeModal (object) {
    $('#myModal').modal('show');
    $('#myModalLabel').text('Enter Seat Number');
    $('.addSeatNumber').click(function () {
        var seatNumber = $('#seatNumberHolder').val();
        $(object).addClass('activated').attr('data-seatNumber',seatNumber).text(seatNumber);
        $('#myModal').modal('hide');
    });
}
function pushSeat (object) {
    var object = '#'+object.attr('id');
    if($(object).hasClass('activated')) {
        $(object).removeClass('activated').html('');
    }
    else {
        changeModal(object);
    }
};
$(document).on('click', '.seat',function(e) {
        var id = $(this);
        e.stopPropagation();
        pushSeat(id);
});


function CreateTheatre () {
    this.rows = 20, this.columns = 10;
    this.seatRowName  = function (a) {
        return String.fromCharCode(a.charCodeAt(0) + 1);
    }
    this.render = function () {
        var layout = '';
        var seatRowStart = 'A';
        for (var i = 0; i < this.columns; i++) {
            layout += '<div class="seatRow">'+seatRowStart+'</div>';
            if (seatRowStart == 'Z') {
                seatRowStart = '`';
            }
            seatRowStart = this.seatRowName(seatRowStart);
            for (var j = 0; j < this.rows; j++) {
                layout += '<div id="'+seatRowStart+(j+1)+'" class="seat"></div>';
            }
            layout += '<div class="clear"></div>';
        }
        $('.seatContainer').html(layout);
    };
};

1 个答案:

答案 0 :(得分:0)

我移动了我的$('。addSeatNumber')。点击(函数(){从模态框输出并使用全局变量来存储最终元素I​​D。

var myHack;
function changeModal (object) {
    $('#myModal').modal('show');
    $('#myModalLabel').text('Enter Seat Number');
    myHack = object;
}
function pushSeat (object) {
    var object = '#'+object.attr('id');
    if($(object).hasClass('activated')) {
        $(object).removeClass('activated').html('');
    }
    else {
        changeModal(object);
    }
};


$(document).on('click', '.seat',function(e) {
        var id = $(this);
        e.stopPropagation();
        pushSeat(id);
});
$('#addTheatre').click(function () {
    saveTheatre();
})
$('.addSeatNumber').click(function () {
    var seatNumber = $('#seatNumberHolder').val();
    $(myHack).addClass('activated').attr('data-seatNumber',seatNumber).text(seatNumber);
    $('#myModal').modal('hide');
});