当单击按钮时,关键字$(this)的行不起作用 - jQuery

时间:2013-02-27 11:27:26

标签: jquery

var undoButton = $('<input type="button" id="undoBtn" value="UndoSelection">').addClass('button');
        $(windowContainer).append(undoButton);
        $(undoButton).click(function(){
            var seat = $('<img/>',{src:'gfx/seat.png'});
            var seatYellow = $('<img/>',{src:'gfx/seat_yellow.png'});
            if(($('td').hasClass('p')) && ($('td').hasClass('picked'))){  
                **$(this).html(seatYellow);**                                   
            } else if (($('td').hasClass('n')) && ($('td').hasClass('picked'))){
                **$(this).html(seat);**
            }

        })

$(this).html(seatYellow)$(this).html(seat)不起作用。当我通过(this)补充单词('td')时,if语句的第一部分将显而易见,因为它返回true。然而,这不是我想要的。我希望将特定的td元素替换为seatseatYellow,这就是我使用(this)的原因。出于某种原因,它不起作用。有任何想法吗? 先感谢您。

2 个答案:

答案 0 :(得分:0)

试试这个:

$(windowContainer).on('click', undoButton, function() {

或者这样:

$(windowContainer).on('click', '.button', function() {

delegate the event to document

$(document).on('click', undoButton, function() {

或者这个:

$(document).on('click', '.button', function() {

答案 1 :(得分:0)

考虑将html与图像数据应用于何处。目前,您正尝试使用值undoButton将图像添加到输入标记中。

您需要记住对要添加座位的元素的引用。

var el = $(this);
var undoButton = $('<input type="button" id="undoBtn" value="UndoSelection">').addClass('button');
$(windowContainer).append(undoButton);
$(undoButton).click(function(){
    var seat = $('<img/>',{src:'gfx/seat.png'});
    var seatYellow = $('<img/>',{src:'gfx/seat_yellow.png'});

    if(($('td').hasClass('p')) && ($('td').hasClass('picked'))){  
        el.html(seatYellow);                                 
    } else if (($('td').hasClass('n')) && ($('td').hasClass('picked'))){
        el.html(seat);
    }
});

最好只将一个类应用于当前座位,并将图像设置为背景图像,具体取决于它是普通座位还是黄色座位。