问题描述
我有一个函数和一些代码:
函数findMember(str){
// console.log ('search:'+ str);
$ b $ .post(includes / search.php,{
search:str,
},function(data,status){
// console。 log(data);
$('#creatorSearchMain')。html(data);
});
$ b $('#creatorSearchInput')。keyup(function(){
var target = $('#creatorSearchInput');
findMember(target.val()); //删除并取消注释其他如果要在请求前等待
});
这将从输入中选择文本并将其与.post一起用于查询数据库以搜索用户搜索的名称。 .post返回添加到div的html代码。
在返回的html中有一个按钮:
< button class =followButtontype =submitvalue =1>关注< / button>
当点击该按钮时,它会运行另一个javascript函数。
除了在使用.html添加返回给div的html之后单击按钮时,这一切都完美无缺。
澄清,该按钮在第一次加载页面时起作用,并且它在那里,但是当我将它放回新的结果中时,它似乎不会被javascript拾取。
$('。followButton')。on(点击,function(){
#code in here
});
提前致谢!
您的按钮正在动态添加,请使用 使用 添加点击处理程序,
$(#creatorSearchMain)。on click,。followButton,function(){
#code in here
});
* on()
之前的选择器, $(#creatorSearchMain)
在这里,应该是一个静态元素。
I have a function and some code:
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
});
This selects the text from an input and uses it with .post to query the database to search for a user with the name searched. The .post returns html code that is added to a div.
In that html that is returned there is a button:
<button class="followButton " type="submit" value="1">Follow</button>
When that button is clicked it runs another javascript function.
This all works perfectly except for when I try and click the button after I have used .html to add the html returned to the div.
To clarify, the button works when the page is first loaded and it is there but when I put it back there with the new results it does not seem to be picked up by the javascript.
This is what I am using to activate the onclick button function:
$('.followButton').on("click", function() {
#code in here
});
Thanks in advance!
Your button is being added dynamically, use event delegation using on()
for adding click handlers to it,
$("#creatorSearchMain").on("click",".followButton", function() {
#code in here
});
*The selector before on()
, $("#creatorSearchMain")
here, should be a static element.
这篇关于Jquery没有通过点击动态添加按钮来调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!