单击动态添加按钮时Jquery不调用函数

我有一个函数和一些代码:

function findMember(str) { // console.log('search: ' + str); $.post("includes/search.php", { search: str, }, function(data, status) { // console.log(data); $('#creatorSearchMain').html(data); }); } $('#creatorSearchInput').keyup(function() { var target = $('#creatorSearchInput'); findMember(target.val()); //remove and uncomment other if want to wait before request }); 

这将从输入中选择文本并将其与.post一起使用以查询数据库以搜索具有搜索名称的用户。 .post返回添加到div的html代码。

在返回的html中有一个按钮:

  

单击该按钮时,它会运行另一个javascript函数。

除了在我使用.html添加返回到div的html后尝试单击按钮时,这一切都完美无缺。

为了澄清,该按钮在页面首次加载时起作用并且它在那里但是当我把它放回到新的结果时它似乎没有被javascript拾取。

这是我用来激活oncl​​ick按钮function的方法:

 $('.followButton').on("click", function() { #code in here }); 

提前致谢!

您的按钮是动态添加的,使用on()使用事件委派为其添加点击处理程序,

 $("#creatorSearchMain").on("click",".followButton", function() { #code in here }); 

*此处的on()$("#creatorSearchMain")之前的选择器应该是一个静态元素。

使用该代码:

 $('#creatorSearchMain').on("click", '.followButton', function() { #code in here });