简体   繁体   English

使用未命名的函数将元素绑定/取消绑定到JS事件处理程序

[英]Bind/Unbind element to JS Event Handler with unnamed function

I have a very basic doubt... 我有一个非常基本的疑问...
In my wordpress blog, in my custom metabox, 在我的wordpress博客中,在我的自定义metabox中,
This is my event handler : 这是我的事件处理程序:

jQuery('tr input.test').on('click', function( event ){
    event.preventDefault();
    var index = jQuery(this).closest('tr').index();
    set_row_index(index);
    .
    .
    .
    });

I have a table with last column having button (input type->submit) "Edit". 我有一个表的最后一列具有按钮(输入类型->提交)“编辑”。 On adding a row dynamically, the "Edit" button of newly added row does not works. 动态添加行时,新添加的行的“编辑”按钮不起作用。

jQuery('tr #confirm_add').on('click',function(){
   event.preventDefault();

  .
  .
  .
   html += "<td> <input type=\"submit\" id=\"select\" value=\"Edit\"></td>";
   .
   .
   .
   $('#metabox_row').prepend(html);

   // BIND ELEMENT HERE
});

I need to bind this event handler to the Edit button. 我需要将此事件处理程序绑定到“编辑”按钮。 Please help on how to achieve this 请帮助如何实现这一目标

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call. 当前,您所使用的被称为“直接”绑定,它将仅附加到您的代码进行事件绑定调用时页面上存在的元素。

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically. 动态生成元素时,需要使用.on()委托事件方法使用事件委托。

Script 脚本

$('#metabox_row').on('click', "input.select'", function(){
    //Your code
});

Change the type to button 将类型更改为button

html += "<td> <input type=\"button\" id=\"select\" value=\"Edit\"></td>";

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. 委托事件的优点是,它们可以处理以后在后代添加到文档中的后代元素中的事件。 By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers. 通过选择在附加委托事件处理程序时保证存在的元素,我们可以使用委托事件将click事件绑定到动态创建的元素,并且还避免了频繁附加和删除事件处理程序的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM