在 keyup 事件中分配点击事件处理程序会导致多次触发点击事件

Assigning click event handler inside keyup event causes the click event to be fired multiple times

我试图仅在填充某些表单字段时向锚点添加事件处理程序,如下所示:

$('#newName, #newFrom').keyup(function (e) {
    if ($('#newName').val() || $('#newFrom').val()) {
        $('#add-person').click(function (e) {
            //Handle event, includes adding a row to a table.
            $('this').off();
        });
    }
});

似乎第一个事件正在传播到第二个事件,因为我最终 table 中的行数与我键入的键数相同。

我试过添加

    e.stopPropagation();

但是没有成功。

$('this').off(); 应该是 $(this).off();
也可能您最好使用 input 事件而不是 keyupinput 即使将内容粘贴到您的字段中,事件也会触发。

尽管如此,我还是会走另一条路:

// (cache your selectors)
var $newName = $("#newName"),
    $newFrom = $("#newFrom");

// create a boolean flag
var haveNewValue = false;

// modify that flag on fields `input`
$newName.add( $newFrom ).on("input", function() {
  haveNewValue = ($.trim($newName.val()) + $.trim($newFrom.val())).length > 0;
});

// than inside the click test your flag
$('#add-person').click(function (e) {
  if(!haveNewValue) return; // exit function if no entered value.

  // do stuff like adding row to table
});

哪里出了问题:

在每个 keyup 上,您都为按钮分配了一个新的(因此是多个)click event/s,但是(更正为:) $(this).off() 仅在实际单击按钮后触发。

还有一个更好的方法来使用.on()off.()(注意使用.click()方法和.on()方法的区别)是:

function doCoffee() {
  alert("Bzzzzzzzz...BLURGGUZRGUZRGUZRG");
}

$("#doCoffeeButton").on("click", doCoffee); // Register "event" using .on()

$("#bossAlertButton").click(function() {
   $("#doCoffeeButton").off("click");       // Turn off "event" using .off()
});