jQuery,点击事件,过多的递归

Mar*_*rek 5 jquery click

有人能告诉我为什么这段代码:

$('#places-view > tbody').find('td').click(function(evt) {
    var td = $(this),
        input = td.find('input');
        console.log('click');
        console.log(input.attr('disabled'), 'disabled');
        if (! input.attr('disabled')) {
            input.trigger('click');
            console.log('inner click');
        }
})
Run Code Online (Sandbox Code Playgroud)

抛出过多的递归错误......

问候

use*_*716 6

要防止事件冒泡,请将元素的click事件放在event.stopPropagation()处理程序中input.

$('#places-view input').click(function(event) {

      // This will prevent the click event from bubbling up and firing
      //    the click event on your <td>
    event.stopPropagation();

      // run the rest of your click code
});
Run Code Online (Sandbox Code Playgroud)

http://api.jquery.com/event.stopPropagation/


编辑:正如@Pointy指出的那样,你可能打算让同一个处理程序处理这两个事件,或者至少让td你在点击时处理程序仍然会触发input.

如果是这种情况,您只需要检查td处理程序是否通过单击而触发input,如果是,则阻止input.trigger("click")运行:

$('#places-view > tbody').find('td').click(function(evt) {
    var td = $(this),
        input = td.find('input');
        console.log('click');
        console.log(input.attr('disabled'), 'disabled');
        if (! input.attr('disabled')) {
                // If the target of the click was not the input,
                //   then trigger the click on the input
            if( input.not( evt.target ).length ) {
                input.trigger('click');
                console.log('inner click');
            }
        }
});
Run Code Online (Sandbox Code Playgroud)

另一种进行测试的方法是:

if(input[0] != evt.target) {...
Run Code Online (Sandbox Code Playgroud)

这两种方法都假设只有一种方法input.如果不是这种情况,那么您需要为输入提供一个标识符,以使测试更具体.


Poi*_*nty 1

当您触发“单击”时,它实际上并不是一个单独的事件调度循环 - jQuery 将立即运行处理程序。由于您<input>位于您的内部<td>,因此该事件将冒泡到其<td>自身,在那里它将再次撞到该处理程序。

另请注意此处的这一行:

console.log(input.attr('disabled'), 'disabled');
Run Code Online (Sandbox Code Playgroud)

也许不是你想要的 - 我认为总会记录“禁用”这个词。也许你的意思是

console.log(input.attr('disabled') + ' disabled');
Run Code Online (Sandbox Code Playgroud)