使用jquery动态添加按钮

时间:2021-05-18 20:29:10

I've got an mvc app in .net that i'm trying to dynamically add buttons. Below is a sample of the jquery i'm using. It's a fairly long sequence of html that's appended but it works and those buttons are added. But when the buttons click they don't seem to activate a click event handler that i've got.

我在.net中有一个mvc应用程序,我正在尝试动态添加按钮。下面是我正在使用的jquery的示例。它是一个相当长的html序列,但它可以工作并添加了这些按钮。但是当按钮单击时,它们似乎不会激活我所拥有的单击事件处理程序。

$('#imageCont').append('<div class="row tier" id="tier'+ tierIdCount +'"  ><hr/><h3>Tier</h3><button type="button" class="btn btn-default addPerson">Add Person</button><button type="button" class="btn btn-default removePerson">Remove Person</button></div>');

Thanks.

1 个解决方案

#1


2  

I imagine you have event handler with jQuery like this:

我想你有像这样的jQuery事件处理程序:

$('.removePerson').on('click', 
   function(e){
       //do some stuff
   });

And if you changed this first line with

如果你改变了第一行

$(document).on('click', '.removePerson',
   function(e){
       //do some stuff
   });

everything should start working as you expect. Dynamically added html elements have to use delegated events, because listeners are attached to elements which are already present in DOM

一切都应该按照你的期望开始工作。动态添加的html元素必须使用委托事件,因为侦听器附加到DOM中已存在的元素

#1


2  

I imagine you have event handler with jQuery like this:

我想你有像这样的jQuery事件处理程序:

$('.removePerson').on('click', 
   function(e){
       //do some stuff
   });

And if you changed this first line with

如果你改变了第一行

$(document).on('click', '.removePerson',
   function(e){
       //do some stuff
   });

everything should start working as you expect. Dynamically added html elements have to use delegated events, because listeners are attached to elements which are already present in DOM

一切都应该按照你的期望开始工作。动态添加的html元素必须使用委托事件,因为侦听器附加到DOM中已存在的元素