Jquery - 将event.data传递给.on()和.bind()

时间:2022-04-05 18:54:41

As I understand it, future versions on jQuery will not have bind so I am trying to use on instead. I have run into a problem though.

据我所知,jQuery上的未来版本将不会绑定,所以我试图改用。我遇到了一个问题。

I am trying to understand why bind allows me to set event.data but on doesn't.

我试图理解为什么bind允许我设置event.data但是没有。

This works

$(document).bind('ajaxError', '#form-id', function(event, jqxhr, settings, exception){
  $(event.data).render_form_errors($.parseJSON(jqxhr.responseText));
});

This doesn't work

这不起作用

$(document).on('ajaxError', '#form-id', function(event, jqxhr, settings, exception){
  $(event.data).render_form_errors($.parseJSON(jqxhr.responseText));  
});

I have multiple forms on a single page so I am trying to render the error for each specific form.

我在一个页面上有多个表单,所以我试图为每个特定表单呈现错误。

1 个解决方案

#1


4  

That's because the second argument to on() is a selector, not the event data (as on() is also meant to supersede delegate()).

那是因为on()的第二个参数是一个选择器,而不是事件数据(因为on()也意味着取代delegate())。

The correct syntax for on() in your case is:

在您的情况下on()的正确语法是:

$(document).on('ajaxError', null, '#form-id', function(event, jqxhr, settings, exception) {
    $(event.data).render_form_errors($.parseJSON(jqxhr.responseText));  
});

As an aside, note that, to my knowledge, no official source has said that future versions of jQuery will not have bind(). on() is indeed meant to supersede both bind() and delegate(), but neither method is deprecated and both will most probably remain around in the foreseeable future (there is a lot of code out there that still uses them).

顺便说一句,请注意,据我所知,没有官方消息称未来版本的jQuery不会有bind()。 on()确实意味着取代bind()和delegate(),但是这两种方法都不被弃用,并且在可预见的将来两者都很可能保持不变(有很多代码仍在使用它们)。

#1


4  

That's because the second argument to on() is a selector, not the event data (as on() is also meant to supersede delegate()).

那是因为on()的第二个参数是一个选择器,而不是事件数据(因为on()也意味着取代delegate())。

The correct syntax for on() in your case is:

在您的情况下on()的正确语法是:

$(document).on('ajaxError', null, '#form-id', function(event, jqxhr, settings, exception) {
    $(event.data).render_form_errors($.parseJSON(jqxhr.responseText));  
});

As an aside, note that, to my knowledge, no official source has said that future versions of jQuery will not have bind(). on() is indeed meant to supersede both bind() and delegate(), but neither method is deprecated and both will most probably remain around in the foreseeable future (there is a lot of code out there that still uses them).

顺便说一句,请注意,据我所知,没有官方消息称未来版本的jQuery不会有bind()。 on()确实意味着取代bind()和delegate(),但是这两种方法都不被弃用,并且在可预见的将来两者都很可能保持不变(有很多代码仍在使用它们)。