jQuery事件处理程序.on()不起作用 [英] jQuery event handler .on() not working

查看:22
本文介绍了jQuery事件处理程序.on()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个事件附加到动态创建的元素类.所以我使用了实时功能,但它没有被触发.所以检查了live function reference,下面有红色的注释

I want to attach a event to dynamically created element class.So i used live function but it was not triggered. So checked live function reference ,there i red below notes

从 jQuery 1.7 开始,不推荐使用 .live() 方法.使用 .on() 来附加事件处理程序.旧版本 jQuery 的用户应该使用.delegate() 优先于 .live().

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

所以决定使用 on 功能,但它仍然不起作用.文本字段已经附加了 jquery ui datpicker.在另一个元素上选择我禁用了该字段.

so decide to use on function,But it still not working.The text field is already attached with jquery ui datpicker.On another element select i disabled that field.

jQuery("#from").attr('disabled','disabled')
.removeClass('date_picker_bg')
.removeClass('hasDatepicker')
.addClass('date_picker_disabled');

如果我点击禁用后我想显示警报或工具提示.所以我尝试了这个,但没有工作

after disabled if i click i want to show alert or tooltip.so i tried this,but not working

jQuery(".date_picker_disabled").on("click", function(event){
          alert('hi');
  });

可能是什么问题

我正在使用 jquery 1.7.1 (jquery-1.7.1.min.js)

I am using jquery 1.7.1 ( jquery-1.7.1.min.js)

推荐答案

问题是 jQuery(".date_picker_disabled") 找到具有该类的元素并绑定到它们.如果元素在绑定时没有类,则不会处理事件.

The problem is that jQuery(".date_picker_disabled") finds elements with that class and binds to them. If elements don't have the class at the time the binding is made, the events will not be handled.

on 函数允许您在事件冒泡"到父元素时通过在另一个元素上处理它们来解决这个问题.在这种情况下,我们可以说 body 元素——您可以选择更具体的共同父元素.

The on function allows you to get round this by handling them on another element when the event "bubbles up to" a parent element. In this instance, we could say the body element – there may be a more specific common parent you could choose.

jQuery(document.body).on('click', '.date_picker_disabled', function(event) {
    alert('hi');
});

事件处理程序现在绑定到 document.body 元素.所有在正文中任何地方发生的点击都会被测试以查看它们是否来自与选择器匹配的元素.如果是,则触发处理程序.

The event handler is now bound to the document.body element. All clicks that happen anywhere in the body are tested to see if they originated from an element matching the selector. If so, the handler is fired.

这在 on 函数的文档中有解释.它与以前版本的 jQuery 中的行为相同,带有 livedelegate 函数.

再次查看您的代码后,您在 input 元素上设置了 disabled="disabled".click 事件不会在禁用的元素上触发.

Having taken another look at your code, you have disabled="disabled" set on your input element. click events are not fired on disabled elements.

这篇关于jQuery事件处理程序.on()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆