在keyup事件中指定click事件处理程序会导致click事件被多次激发

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

本文关键字:click 事件 程序 keyup 事件处理      更新时间:2024-01-10

只有在填充了某些表单字段时,我才试图将事件处理程序添加到锚点,如下所示:

$('#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();
        });
    }
});

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

我试着添加

    e.stopPropagation();

但没有成功。

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

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

// (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事件/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()
});