简体   繁体   English

使用jquery为动态创建的特定元素添加事件监听器

[英]Add Event Listener for dynamically created particular element using jquery

I'm creating dynamic elements using jquery and try to bind listener for elements. 我正在使用jquery创建动态元素,并尝试为元素绑定侦听器。 by binding listener using 通过使用绑定听众

$('#div11').on('click',$('#textbox31'),function(e){showPopupImage(e);});
$('#div11').on('click',$('#textbox32'),function(e){alert('hi');});

function,it adds listener to descendents even though i specify the particular field to bind. 函数,即使我指定要绑定的特定字段,它也会向后代添加侦听器。

pls,suggest me the good way to handle my situation. 请给我建议处理我情况的好方法。

The problem is that you are not specifying the correct parameters to the on function. 问题是您没有为on函数指定正确的参数。 If you look at the JQuery documentation, you are using the following function overload: 如果您查看JQuery文档,则会使用以下函数重载:

.on( events [, selector ] [, data ] ) .on(事件[,选择器] [,数据])

The part you are specifying incorrectly is the selector parameter. 您指定不正确的部分是selector参数。 This parameter requires a selector string, not a JQuery objct. 此参数需要选择器字符串,而不是JQuery objct。

The following will work: 以下将起作用:

$('#div11').on('click','#textbox31',function(e){showPopupImage(e);});
$('#div11').on('click','#textbox32',function(e){alert('hi');});

Notice I have replaced $('#textbox31') with '#textbox31' . 请注意,我已经取代$('#textbox31')'#textbox31'

Here is a working example , you will see that the click event is not applied to textbox33 and textbox34 这是一个工作示例 ,您将看到click事件未应用于textbox33textbox34

Try it : 试试吧 :

$('#div11').on('click', '#textbox31',function(e){
        showPopupImage(e);
});
$('#div11').on('click', '#textbox32', function(e) {
  //do something
});

Using .on() you can define you function once, and it will execute for any dynamically added elements. 使用.on()可以定义一次功能,它将对任何动态添加的元素执行。

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

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