在我的wordpress主题中,我使用api来加载电影信息。所以,我试图调用jquery函数,它将执行ajax请求并加载结果在预定义的DIV。
但是当我在content。php页面中调用这个函数时,文档。准备还没有完成。因此,要么我需要在document.ready()之外定义jquery函数(我认为这不是一个好主意),要么我需要在bodyOnload上调用该函数。在后一种情况下,我不确定如何从页面内容中包含使用wordpress的get_the_content()函数解析的url。
谁能告诉我一下。
PHP (content.php):$pattern = '/REGEX/i';
$replacement = '$1';
$subject = get_the_content();
$urls = preg_split($pattern, $subject); // Let say I have all the links in this variable
echo '<script>loadMovies('.json_encode($urls).');</script>'; // loadMovies() is not available at this point
现在loadMovies()在custom.js中定义,如下所示
jQuery(document).ready(function () {
"use strict";
function loadMovies(urls){
console.log(urls);
// HERE I HAVE MY AJAX CALLS WHICH IS NOT AN ISSUE
// THE MAIN ISSUE IS THE FUNCTION IS NOT AVAILABLE AT THE POINT I CALL IT
}
});
custom.js在functions.php
中添加function test_call_js(){
wp_enqueue_script(
'custom-js',
get_stylesheet_directory_uri() . '/js/custom.js',
array( 'jquery' )
);
}
add_action('wp_enqueue_scripts', 'test_call_js');
您有一个范围问题。您在另一个函数中声明该函数,这意味着当您添加脚本时,它将不会从全局作用域可见。您需要将从全局作用域的其他脚本中调用的函数移到全局作用域中。
AJAX调用仍然可以放在ready事件中,因此它将在DOM准备好后加载脚本。
就像- 4所说的,这是一个时间问题。你正在调用一个只在dom ready上创建的函数。解决方案是在dom就绪时调用ajax函数,并只输出脚本前面(调用ajax函数的地方)中该函数所需的变量
。content.php
$urls = preg_split($pattern, $subject); // Let say I have all the links in this variable
echo '<script> var urls='.json_encode($urls).';</script>';
注意,你所做的只是在这里定义url,这是不好的标记,但它需要在这里,因为你正在使用the_content()
,需要在wp循环中运行。
在你的js文件
function loadMovies(urls){
console.log(urls);
// define our function.
}
jQuery(document).ready(function () {
loadMovies(urls){
console.log(urls);
// call our predefined function
}
});
仍然可以在文档中定义函数。现成的函数,但是创建函数然后在其他函数中调用更简洁(在上面的例子中它是一个匿名函数)