[英]jQuery doesn't like .on and .append?
I have a weird problem. 我有一个奇怪的问题。 I'm currently working on loading posts using PHP, AJAX and MySQL.
我目前正在使用PHP,AJAX和MySQL加载帖子。 The code structure itself looks like this:
代码结构本身如下所示:
--- main.js --- -main.js-
$(window).load(function(){
initAjax();
});
--- ajax.js --- -ajax.js-
function initAjax(){
// Toggles a navigation
$(document).on('click', '.btn.open', function(){
... toggles a window ...
});
// Add new posts
$(document).on('click', '.btn.refresh', function(){
$.ajax({
... ajax stuff ...,
success: function(html){
// Show new posts
$('.post_container').prepend(html);
}
});
});
}
When I append new posts they'll show up, but I am not able to click .btn.open anymore - Shouldn't 'on()' fix this? 当我添加新帖子时,它们会出现,但我无法再单击.btn.open-'on()'是否可以解决此问题? When I go to the Google Chrome console.
当我转到Google Chrome控制台时。
Does somebody know a potential way to solve the problem? 有人知道解决问题的潜在方法吗?
FIXED! 固定! @ cmorrissey found a small solution by replacing $(document) with $('body')
@ cmorrissey通过用$('body')代替$(document)找到了一个小解决方案
This fix doesn't seem to be a perfect solution since $(document) normally has to work! 由于$(document)通常必须正常工作,因此此修补程序似乎不是完美的解决方案! Since I want clean code, I am totally going to try out @ Potherca 's Short, Self Contained, Correct, Example method and probably I'll find the solution this way.
由于我想要干净的代码,因此我将完全尝试@ Potherca的简短,自包含,正确,示例方法,也许我会以这种方式找到解决方案。 Thanks
谢谢
You need to use 'body'
or document.body
instead of document
. 您需要使用
'body'
或document.body
而不是document
。
$('body').on('click', '.btn.refresh', function(){
$.ajax({
... ajax stuff ...,
success: function(html){
// Show new posts
$('.post_container').prepend(html);
}
});
});
Reason: The addition of content to the body doesn't bubble up to the document level ( http://bugs.jquery.com/ticket/11621 ), it looks like you can also use window
原因:向正文添加的内容不会达到文档级别( http://bugs.jquery.com/ticket/11621 ),看起来您也可以使用
window
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.