$(this)参考

时间:2013-03-06 04:08:35

标签: javascript jquery

$('td').click(function(){    
    $('input:radio').click(function(){    
    })
})

如果我在第二行之后使用$(this),它将引用单选按钮。如何从该行引用td元素?我正在尝试向td元素添加一个id,但它将它添加到单选按钮。

3 个答案:

答案 0 :(得分:4)

在单选按钮处理程序之前保存对此的引用:

$('td').click(function () {
    var self = this;
    $('input:radio').click(function () {
        // self refers to 'this' from the td selection here
    });
});

我不确定这是你真正想做的事情,但是,正如你所做的那样是为点击td上的单选按钮分配一个点击处理程序。那是你的想法吗?

答案 1 :(得分:1)

有两种方法可以做到:

正如其他人所示,您可以使用闭包:

$('td').click(function() {
    var td = this; // Creates a closure
    $('input:radio').click(function(event) {
        // this and event.target refer to the radio button
        // td refers to the <td> element
    });
});

或者您可以使用$.prox()

$('td').click(function() {
    $('input:radio').click($.proxy(function(event) {
        // this refers to the td
        // event.target refers to the radio button
    }, this));
});

答案 2 :(得分:0)

$('td').click(function(){    
    var tdElement = $(this);
    $('input:radio').click(function(){    
        // Do whatever you like with tdElement here
    })
})