2

我希望我把问题说清楚了。

假设您有一些复选框(或任何其他类型的元素),您在页面加载时为其注册事件处理程序。然后使用 AJAX 添加更多复选框(因此无需重新加载页面)。但是您还希望这些新添加的复选框(在页面加载后)具有相同的注册事件处理程序吗?

我尝试的是这样,但我觉得必须有更好的方法:

$(document).ready(function () {

  // Register custom envets handler
  registerCustomEventHandlers();

  $('a').on('click', addExtraFields);
});

function registerCustomEventHandlers() {
  $('input.class_name').on("change", sayHelloWorld);
}

function sayHelloWorld() {
  alert('Hello world');
}

function addExtraFields() {
  // insert some checkboxes...

  // register the events handler again for the newly added fields
  registerCustomEventHandlers();
}

所以基本上在添加复选框的函数中,我再次注册了所有事件处理程序。我正在看类似的东西,$(document).change(function() {});但显然并非所有浏览器都支持它......

有什么建议么?

4

4 回答 4

2

您可以将事件委托给,document以便它们也将应用于所有未来的输入。你甚至不需要把它放在一个domReady事件中,因为document它总是可用的:

$(document).on("change", "input.class_name", sayHelloWorld);

function sayHelloWorld() {
    alert('Hello world');
}

function addExtraFields() {
    // insert some checkboxes, they will have the same handler attached when inserted
}

演示:http: //jsfiddle.net/gdX3R/1/

于 2012-07-10T12:12:13.977 回答
1

由于这些原因,我建议不要使用实时选择器

简而言之,这是一个性能问题,因为它会干扰每个点击事件。

相反,只需使用输入的最低公共父元素(很可能是表单)的帖子中描述的委托:

$('#yourFormId').delegate('.class_name', 'click', function() { 
   // what you want to do
});

你可以在这里找到一个 jsfiddle

并且不要使用像 input.class_name 这样的选择器(除非输入以外的元素具有该类名)。它们比 .class_name 慢,因为它们循环遍历表单中的所有输入,以搜索具有该类的元素,而不仅仅是按类选择。

于 2012-07-10T12:33:11.440 回答
0

从 jquery 1.4 开始,您也可以随时使用live()http://api.jquery.com/live/ 它允许您现在和将来将处理程序附加到任何匹配的元素。

于 2012-07-10T12:12:45.210 回答
0

在 Jquery 中完成此操作的方式是在创建处理程序时不需要对象存在。

你可以使用:

$(document.body).on("click", "input[type='checkbox']", 
   function(){alert($(this))}
);

这将应用于添加到页面的任何新复选框,无论时间如何。

于 2012-07-10T12:13:19.003 回答