问题描述
请查看此 HTML 代码:
<h2>第一</h2><p>第二</p><div class="grid"><h2>第一</h2><p>第二</p>
请查看此 HTML 代码:
<h2>第一</h2><p>第二</p><div class="grid"><h2>第一</h2><p>第二</p>
我可以使用以下代码更改页面加载时元素的顺序:
$('.grid').each(function(){var p = $(this).find('p'),h2= $(this).find('h2');h2.insertAfter(p);});
但是 ajax 分页有更多的内容,所以我把它包裹在 $(document).ajaxComplete(function(){
现在的问题是我的代码仅在 ajax 内容加载后运行,我希望我的代码在页面加载和 ajax 加载的内容上运行.
感谢您的帮助.
https://jsfiddle.net/j0fozshv/2/
您可以将需要多次执行的内容提取到一个函数中:
function doMyStuff() {$('.grid').each(function(){var p = $(this).find('p'),h2= $(this).find('h2');h2.insertAfter(p);});//或者做你需要的.这只是一个例子}
之后,只需在需要的地方使用您的功能.文档准备就绪:
$(function () {//...doMyStuff();});
如果你在某处有 AJAX 的东西,只需调用它进行成功回调:
//只是一个例子!$(document).ajaxComplete(function() {doMyStuff();});
还有一个使用 jQuery AJAX 的例子:
$.get( "/get_some_data", function( data ) {doMyStuff();});
也许该函数采用一些参数(例如从服务器返回的数据)是有意义的:
function doMyStuff(data) {//做你需要的}
再次为您的 AJAX 内容:
$.get( "/get_some_data", function( data ) {doMyStuff(数据);});
Please see this HTML code:
<div class="grid">
<h2>First</h2>
<p>Second</p>
</div>
<div class="grid">
<h2>First</h2>
<p>Second</p>
</div>
I was able to change order of elements on page load with this code:
$('.grid').each(function(){
var p = $(this).find('p'),
h2= $(this).find('h2');
h2.insertAfter(p);
});
But there is more content coming with an ajax pagination so I wrapped that inside $(document).ajaxComplete(function(){
Problem now is my code runs only after the ajax content is loaded, I want my code to run on both page load and on ajax loaded content.
Thank you for your assistance.
https://jsfiddle.net/j0fozshv/2/
You could extract the stuff you need to do multiple times into a function:
function doMyStuff() {
$('.grid').each(function(){
var p = $(this).find('p'),
h2= $(this).find('h2');
h2.insertAfter(p);
});
// or do what you need. it's just an example
}
And after that, just use your function where you need.On document ready:
$(function () {
// ...
doMyStuff();
});
If you have AJAX stuff somewhere, just call it for success callback:
// just an example !
$(document).ajaxComplete(function() {
doMyStuff();
});
One more example with jQuery AJAX:
$.get( "/get_some_data", function( data ) {
doMyStuff();
});
Maybe it makes sense for that function to take some args (e.g. data that is returned from the server):
function doMyStuff(data) {
// do what you need
}
And again for your AJAX stuff:
$.get( "/get_some_data", function( data ) {
doMyStuff(data);
});
这篇关于在加载和 Ajax 加载的内容上运行 JS 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!