最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add Event Listener for dynamically created particular element using jquery - Stack Overflow

programmeradmin0浏览0评论

I'm creating dynamic elements using jquery and try to bind listener for elements. 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.

I'm creating dynamic elements using jquery and try to bind listener for elements. 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.

Share Improve this question edited Jan 13, 2014 at 11:32 codingrose 15.7k11 gold badges40 silver badges58 bronze badges asked Jan 13, 2014 at 11:32 PravinKumar.RPravinKumar.R 3351 gold badge3 silver badges16 bronze badges 7
  • Try this Link – Govinda Rajbhar Commented Jan 13, 2014 at 11:40
  • Using jquery ! Then why you tagged javaScript? – Voonic Commented Jan 13, 2014 at 11:44
  • @shadow: The javascript tag is valid, JQuery is a javascript library – musefan Commented Jan 13, 2014 at 11:47
  • @musefan But its a library, not native javascript – Voonic Commented Jan 13, 2014 at 11:48
  • @shadow: JQuery is written in javascript, and to use it you must write javascript. The code included in the question is all javascript, so it makes sense to tag it as so – musefan Commented Jan 13, 2014 at 11:54
 |  Show 2 more ments

2 Answers 2

Reset to default 3

The problem is that you are not specifying the correct parameters to the on function. If you look at the JQuery documentation, you are using the following function overload:

.on( events [, selector ] [, data ] )

The part you are specifying incorrectly is the selector parameter. This parameter requires a selector string, not a 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'.

Here is a working example, you will see that the click event is not applied to textbox33 and textbox34

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.

发布评论

评论列表(0)

  1. 暂无评论