jQuery使用.of()删除事件处理程序时出现的问题

jQuery Problems with removing event handler with .off()

本文关键字:问题 程序 事件处理 of 使用 删除 jQuery      更新时间:2023-09-26

我曾尝试删除带有.off()的事件处理程序,但它不起作用。

我想从一个特定的输入中删除所有事件处理程序:

<input type="file" id="file_upload" name="file_upload" size="50" />

以下是我尝试过的:

$('#form').on('keyup change', ':input', function() {
    registerChange();
});
$('#form input[name=file_upload]').off();
$('#file_upload').off();

您可以为文件上传按钮使用not选择器

$('#form').on('keyup change', 'input:not([name=file_upload])',  function() {
  registerChange($(this).val());
});
function registerChange(value) {
  // notice that typing into the upload textbox does not log anything to the console
  console.log(value);
}
$('#form').on('click', 'input[name=file_upload]', function () {
  alert('In Click Event Handler, Now Removing Myself');
  // here is how you can remove an event handler
  $('#form').off('click', 'input[name=file_upload]');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form">
  <input type="text" />
  <input type="text" />
  <!-- just changeing this to a textbox for demo -->
  <input type="text" id="file_upload" name="file_upload" size="50" value="Choose file" />
</form>

打开控制台窗口(chrome中的CTRL+SHIFT+J),然后在所有文本框中键入。请注意,只有前两个文本框是如何写入控制台的。还要注意,最后一个文本框定义了一个点击处理程序,然后将其删除,这就是为什么警报只显示一次的原因。

您正在将事件绑定到表单元素。所以为了删除它,你需要再次使用表单标签:

// bind delegated events to form element
$('#form').on('keyup change', ':input', function () {
    registerChange();
});
// remove events later
$('#form').off();

您可能对事件委派感到困惑:on方法的这种用法将事件附加到form元素,在从子级:input冒泡后捕获这些事件。

试试这个:

$('#file_upload').off('keyup change', ':input', function()
{
    registerChange();
});