简体   繁体   English

单击时无法按预期在动态创建的元素上正常工作

[英]on click not working as expected on dynamically created elements jQuery

I have a tag when clicked alerts the data-value of the tag. 单击鼠标后我有一个标签,它会提醒标签的数据值。 It works fine , but doesn't works when i click on dynamically created elements. 它工作正常,但是当我单击动态创建的元素时不起作用。

<img id="no_p_fav" src="http://localhost:8000/icons/non_star.png">

Below is how i create dynamic elements 以下是我如何创建动态元素

 $('.all_candidate_bar').prepend('<div id = "icons"> <a class = "favorite" data-value = "'+data.msg.id+'" > <img id = "no_p_fav" src="{{url("/icons/non_star.png")}}" ></img></a></div>');

Below function doesn't work on dynamically created elements but works fine on elements which were there when the page was loaded. 下面的功能不适用于动态创建的元素,但可以很好地处理加载页面时存在的元素。

$(document).ready(function(){

    $('.favorite').on('click',function(){
        var candidate_id = $(this).data('value');
        alert(candidate_id);
    }); 
});

I have also tried this 我也尝试过

 $('#icons').on('click','a.favorite',function(){//myFunction});
 $('a').on('click','.favorite',function(){//myFunction});

How do i make it work for elements for both dynamic and static elements ? 如何使它适用于动态和静态元素?

Since the #icon is also created dynamically you cannot use event delegation against it, you need a higher level element that is there since the beginning, body for instance: 由于#icon也是动态创建的,因此您不能对其使用事件委托,因此您需要一个自开始就存在的更高级别的元素,例如body

$('body').on('click','.favorite',function(){//myFunction});

The a also won't work, since the event is not delegated in this case, it is accessing the element itself a也将不起作用,因为在这种情况下未委托事件,因此它正在访问元素本身

$('a').on('click','.favorite',function(){//myFunction}); // won't work

Try this Code: 尝试以下代码:

$(document).ready(function(){

    $(document).on('click','.favorite',function(){
        var candidate_id = $(this).data('value');
        alert(candidate_id);
    }); 
});

For dynamically created element you need to to delegate the event $(document).ready(function(){ 对于动态创建的元素,您需要委派事件$(document).ready(function(){

    $('body').on('click','.favorite',function(){
        var candidate_id = $(this).data('value');
        alert(candidate_id);
    }); 
});

change your function like this way 像这样改变你的功能

$(function(){
   $(document).on('click','.favorite',function(){
      var candidate_id = $(this).data('value');
      alert(candidate_id);
});

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

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