使 jquery .on 函数与 AJAX 加载的内容一起工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10416689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making jquery .on function work with AJAX loaded content
提问by zealisreal
I am having trouble getting an .on 'click' function to work upon AJAX loaded content.
我无法使用 .on 'click' 函数处理 AJAX 加载的内容。
I have worked with the jquery .live before but this is the first time with .on and understand it works in the exact same way so unsure why I am having problems.
我之前使用过 jquery .live 但这是第一次使用 .on 并且理解它以完全相同的方式工作,所以不确定为什么我遇到问题。
Below is the HTML that gives the element to which you click on
下面是提供您单击的元素的 HTML
<h1>Press & Media</h1>
<div id="back"></div>
<div id="overlay-content">
<span id="edocs" class="tab"></span>
<span id="news" class="tab"></span>
<span id="partners" class="tab"></span>
</div>
Below is the function that loads the AJAX content.
下面是加载 AJAX 内容的函数。
$("#overlay-content").on('click','#news',function() {
var active = 1;
$("#loading").show();
$("#overlay-content").fadeOut(1000, function() {
$.get("http://<? echo ROOT; ?>includes/functions.php", { pressmediaNews: active }, function(data) {
$("#loading").hide(400);
$("#overlay-content").empty().append(data).fadeIn(1000);
});
});
});
This should load the following HTML
这应该加载以下 HTML
<div id="news-left-panel">
<h4>News Section</h4>
<ul>
<li id="newsID2" class="newsYear">
<p>2012</p>
<ul class="newsMonths" style="display:none">
<li>Jan
<ul class="newsArticles" style="display:none">
<li onClick="newsID(2)">test</li>
</ul>
</li>
<li>Feb</li>
<li>Mar</li>
</ul>
</li>
<li id="newsID1" class="newsYear">
<p>2011</p>
<ul class="newsMonths" style="display:none">
<li>Dec
<ul class="newsArticles" style="display:none">
<li onClick="newsID(1)">Test</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Now the above code simply wont execute, show any errors etcetera in firebug.
现在上面的代码根本不会执行,在 firebug 中显示任何错误等。
So I'm a bit lost as to why it wont execute, the alert() even does not execute.
所以我有点不明白为什么它不会执行,alert() 甚至不执行。
回答by adeneo
First make sure you're hitting the target, try this and see if the alert shows :
首先确保你击中了目标,试试这个,看看警报是否显示:
$(function() {
$(document).on('click', '#news', function() {
alert('ok');
});
});
If the alert shows when clicking the #news element, it's ok.
如果单击 #news 元素时显示警报,则没关系。
Now to this line:
现在到这一行:
$.get("http://<? echo ROOT; ?>includes/functions.php",
You are using the shorthand PHP opening, and that needs to be turned on, you could try
你用的是简写的PHP开头,需要开启,你可以试试
<?php echo ROOT; ?>
But what the frack is ROOT, never seen that before, and could not find anything in the PHP manual on ROOT, so I tried on my own server with the newest version of PHP, and got an error as 'ROOT' does not exist, instead it assumed it was a string and just echo'ed "ROOT", so your link would look like:
但是这个问题是 ROOT,以前从未见过,并且在 ROOT 的 PHP 手册中找不到任何内容,所以我在自己的服务器上使用最新版本的 PHP 进行了尝试,但出现“ROOT”不存在的错误,相反,它假设它是一个字符串并且只是回显“ROOT”,所以你的链接看起来像:
$.get("http://ROOTincludes/functions.php",
It it's a variable you have defined somewhere yourself, it should start with a dollarsign, if it's something you've defined with define()
, make sure it's set up correctly and if it's using something like $_SERVER['DOCUMENT_ROOT'];
that's not always something you can access in javascript as it will normally be a folder that is higher then your webroot, and can't be accessed on the clientside but only on the serverside.
它是您自己在某处定义的变量,它应该以美元符号开头,如果它是您定义的东西define()
,请确保它设置正确,并且如果它使用类似$_SERVER['DOCUMENT_ROOT'];
的东西并不总是您可以在 javascript 中访问的东西,因为它会通常是比您的 webroot 更高的文件夹,并且不能在客户端访问,而只能在服务器端访问。
Also, the way you have written it, starting with http://
it should be a domain name.
Try opening view source in you browser and find your ajax function and see what ROOT actually outputs, as the final ouput will be visible in the source, and if it's set using define() in an included config file etc. you can see that it was set up correctly.
此外,您编写它的方式,从http://
它开始应该是一个域名。尝试在您的浏览器中打开查看源代码并找到您的 ajax 函数并查看 ROOT 实际输出的内容,因为最终输出将在源代码中可见,并且如果使用包含的配置文件等中的 define() 进行设置,您可以看到它已正确设置。
Your javascript would also have to be inside a PHP file for PHP to execute, or you would have to modify your server setup to run JS files thru PHP.
您的 javascript 也必须在 PHP 文件中才能执行 PHP,或者您必须修改服务器设置以通过 PHP 运行 JS 文件。
In my opinion just using a path and filename is the right way to do it, try this and pay attention to the console (F12) :
在我看来,只使用路径和文件名是正确的方法,试试这个并注意控制台(F12):
$(document).on('click','#news',function() {
var active = 1;
var XHR = $.ajax({
type: 'GET',
url : '/actualpath/includes/functions.php',
data: { pressmediaNews: active }
}).done(function(data) {
console.log(data);
}).fail(function(e1, e2, e3) {
console.log('error : '+e1+' - '+e2+' - '+e3);
});
$("#loading").show();
$("#overlay-content").fadeOut(1000, function() {
XHR.done(function(data) {
$("#overlay-content").empty().append(data).fadeIn(1000);
$("#loading").hide(400);
});
});
});
回答by ThiefMaster
Use a delegate:
使用委托:
$('#overlay-content').on('click', '#newsID2', function() { });
This will bind the event on #overlay-content
and check for bubbled events if they originated from #newsID2
.
这将绑定事件#overlay-content
并检查冒泡事件是否来自#newsID2
.
As a side-note: You have a typo in your event handler (chikdren
should be children
) and you should really get rid of this ugly onClick
inline event.
作为旁注:您的事件处理程序中有一个错字(chikdren
应该是children
),您应该真正摆脱这个丑陋的onClick
内联事件。
回答by Petah
Should be more like:
应该更像:
$("#overlay-content").on('click', '#newsID2', function() {
....
});
Or in other words:
或者换句话说:
$('.wrapper').on('event', '.target', function() {
...
});
Where .wrapper
is an element that already exists (or the document), and .target
is the element(s) inside the wrapper you want to run the event on.
哪里.wrapper
是已经存在的元素(或文档),以及.target
要在其上运行事件的包装器内的元素。
The live
function is basically equivalent to:
该live
函数基本上等同于:
$(document).on('event', '.target', function() {
...
});
回答by Steve Davis
http://bugs.jquery.com/ticket/11203
http://bugs.jquery.com/ticket/11203
Key sentence
关键句
If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
如果将新 HTML 注入页面,则在将新 HTML 放入页面后选择元素并附加事件处理程序。
To work with this scenario try binding to the document object with a selector parameter:
要处理这种情况,请尝试使用选择器参数绑定到文档对象:
$(document).on('click','#news',function() {...}
回答by Adam
Since you said that you have previously worked with .live() could the issue here be that you're trying to bind your click on something that you append to the document before you append it?
既然你说你以前使用过 .live() ,这里的问题可能是你试图在附加之前将点击绑定到附加到文档的内容上吗?
When you use live, it handles this sort of stuff automatically, but when you don't use live, things generally have to exist on the page before you bind any events to them. If you add something with AJAX, you can't set up click events for those things before you've loaded them in with AJAX. When you use .live() you can do this ahead of time.
当您使用 live 时,它会自动处理这类事情,但是当您不使用 live 时,在您将任何事件绑定到它们之前,页面上通常必须存在这些内容。如果您使用 AJAX 添加某些内容,则无法在使用 AJAX 加载这些内容之前为这些内容设置点击事件。当您使用 .live() 时,您可以提前执行此操作。
I would do it like this:
我会这样做:
$("#overlay-content").on('click','#news',function() {
var active = 1;
$("#loading").show();
$("#overlay-content").fadeOut(1000, function() {
$.get("http://<? echo ROOT; ?>includes/functions.php", { pressmediaNews: active }, function(data) {
$("#loading").hide(400);
$("#overlay-content").empty().append(data).fadeIn(1000);
//put your delegate/call/function,etc here
});
});
});
回答by user1395243
News-left-panel
新闻左面板
year_Month_newsIDYour News's Year, Month, News ID. For example 2012_5_16, 2012_5_17etc
year_Month_newsID您的新闻的年、月、新闻 ID。例如2012_5_16、2012_5_17等
<div id="news-left-panel">
<h4>News Section</h4>
<ul>
<li id="newsID2" class="newsYear">
<p>2012</p>
<ul class="newsMonths" style="display:none">
<li>Jan
<ul class="newsArticles" style="display:none">
<li id="year_Month_newsID">test</li>
</ul>
</li>
<li>Feb</li>
<li>Mar</li>
</ul>
</li>
<li id="newsID1" class="newsYear">
<p>2011</p>
<ul class="newsMonths" style="display:none">
<li>Dec
<ul class="newsArticles" style="display:none">
<li id="year_Month_newsID">Test</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Jquery Function
jQuery 函数
$("#news-left-panel ul li").live("click", function(event) {
var news=(this.id).split("_");
var year=news[0];
var month=news[1];
var newsID =news[2];
$.ajax({
type: "POST",
url: 'http://<? echo ROOT; ?>includes/functions.php',
data: {
year: year,month:month,newsID :newsID
},
error: function(){
$('#news').html( "<p>Page Not Found!!</p>" );
// Here Loader animation
},
beforeSend: function(){
// Here Loader animation
$("#news").html('');
},
success: function(data) {
$('#news').html(data);
}
});
});?
回答by Jeffery To
Are you sure your Ajax call is correct / returning the right HTML?
你确定你的 Ajax 调用是正确的/返回正确的 HTML 吗?
I replaced $.get() with setTimeout() (and simplified a bit) here: http://jsfiddle.net/q23st/
我在这里用 setTimeout() 替换了 $.get()(并简化了一点):http: //jsfiddle.net/q23st/
It seems to work, so I suspect your $.get() isn't returning what it's expected to return.
它似乎有效,所以我怀疑您的 $.get() 没有返回预期返回的内容。