jQuery .on()方法不适用于动态创建的元素 [英] Jquery .on() method not working on dynamically created elements

查看:36
本文介绍了jQuery .on()方法不适用于动态创建的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看了其他问题并尝试了许多可能的解决方案之后,我仍然无法使click事件正确绑定,并且非常感谢您的帮助.我正在一个与api交互的网页,没有服务器,仅进行ajax调用.

After looking at other questions and trying many possible solutions, I still have not been able to get the click event to bind properly and would really appreciate any help. I am working on a webpage that interacts with an api, no server, just making ajax calls.

这是我的HTML:

    <div class = "img image-1 onTop" style="width:300px;left:0px">
      <div class = "pallette-container">
        <div class = "color-sample">
         <div class = "color-overlay">
           <p>#55423</p>
         </div>
        </div>
      </div>
    </div>

当我从ajax请求中获取数据时,我会动态创建这些"img" div和所有子div.

I dynamically create these "img" divs and all the child divs when I get data back from an ajax request.

我需要将click事件函数绑定到'div.color-overlay'元素.

I need to bind a click event function the the 'div.color-overlay' element.

我尝试了许多不同的方法来绑定它,并达到了我认为是使用选择器来抓取元素的最具体方法.

I have tried many different ways to bind it, and have reached what I think is the most specific way to grab the element with selectors.

这是我写的函数:

    $('div.img.onTop.image-1>div.palette-container').on('click', 'div.color-sample>div.color-overlay',function(event){
       var searchValue = $(this).parent().attr('data-color');
       $('#colorvalue').val(searchValue);
    });

请帮助我了解问题所在.我没有逻辑去尝试.非常感谢!我正在使用Jquery 2.1.3.

Please help me understand what is wrong. I am out of logical things to try. Many Thanks! I am using Jquery 2.1.3.

推荐答案

您是从正确的轨道开始的,但是为了完成此工作,您需要将事件处理程序绑定到某个更高级别的元素,例如 body:

You started on the right track, however in order to make this work you need to bind your event handler to some higher level element, for example body:

$('body').on('click', 'div.color-sample>div.color-overlay',function(event){
   var searchValue = $(this).parent().attr('data-color');
   $('#colorvalue').val(searchValue);
});

这里的想法不是处理事件发生的元素上的事件,而是让它冒泡,在这种情况下,直到 body 元素,然后再在此处进行处理.这些就是所谓的委托事件.

The idea here is not to handle event on the element where it happened, but allow it to bubble up, in this case until body element, and then handle it here. These are so called delegated events.

您可以在 jQuery文档中阅读有关委托事件的更多信息,请参阅"直接和委托事件

You can read more about delegated events in jQuery documentation, look at section Direct and delegated events

这篇关于jQuery .on()方法不适用于动态创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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