简体   繁体   English

如何为动态生成的div创建onClick函数

[英]How to create onClick function for a dynamically generated div

I am trying to implement onClick function for a div which is getting generated depending on some validations while submitting the page. 我正在尝试为div实施onClick函数,该div在提交页面时取决于一些验证而生成。 I am trying to implement the same from an external js file. 我正在尝试从外部js文件实现相同的功能。

HTML design is something like : HTML设计类似于:

<div id="QViewInfo" style="top: 207px; left: 531.5px;">
    //dynamically generated
    <div>
    ---
    ----
    </div>
</div>

Now, I am trying to implement the onClick function like below : 现在,我正在尝试实现如下所示的onClick函数:

$('img.popUpClose.popUpCloseQview').each(function (index) {
    $(this).on("click", function (e) {
        //DO something
    });
});

But the issue is, this $('img.popUpClose.popUpCloseQview') element is not there in the code on the first time. 但是问题是,第一次在代码中不存在$('img.popUpClose.popUpCloseQview')元素。 After the submit button click valiations are happening and depending on the condition this pop up message is coming up and this function is not working anytime. 在提交按钮之后,点击状态发生,并且取决于出现的情况,此弹出消息即将出现,并且该功能在任何时候都不起作用。

Tried some other options too. 也尝试了其他一些选择。 But none of these are working. 但是这些都不起作用。

Please advise. 请指教。

Thanks, Aniket 谢谢,Aniket

You could attach the click event to all the div 's of element #QViewInfo using event delegation on() like : 您可以使用事件委托on()将click事件附加到元素#QViewInfo所有div on()例如:

$('#QViewInfo').on('click', 'div', function(){
    //DO something
})

NOTE : No need for using each() loop. 注意:不需要使用each()循环。

Hope this helps. 希望这可以帮助。

 $('#QViewInfo').append('<div>Div 3</div>'); $('#QViewInfo').on('click', 'div', function(){ console.log($(this).text()); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="QViewInfo" style="top: 207px; left: 531.5px;"> <div>Div 1</div> <div>Div 2</div> </div> 

Working snippet with comment code : 带有注释代码的工作片段:

 var img = '<img src="/Images/...." onclick="alert(\\'QView.close();\\')" alt="Close Quick View" class="popUpClose popUpCloseQview">'; $('.oosInfo').append(img); $('#QViewInfo').on('click', 'img.popUpClose.popUpCloseQview', function(){ alert("A"); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="QViewInfo"> <div class="oosInfo"> <div class="alertImgDiv"> <span class="oosAlertImg"></span> </div> </div> </div> 

If you are dynamically generating the div in jquery, you can add the click event then. 如果要在jquery中动态生成div,则可以添加click事件。 For example: 例如:

var div = $("<div>");
div.click(function(){//dostuff});

$("#QViewInfo").append(div);

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

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