[英]After remapping jQuery to $ in my WordPress theme, I can no longer trigger functions from outside the js file
我正在研究一个包含大量jQuery的WordPress主题。 默认情况下,WordPress不允许您使用$
快捷方式,而是必须使用完整的jQuery
- 例如jQuery('.class')
而不是$('.class')
。
这对于几行代码来说并不是太麻烦,但我现在已经有了很多,所以我将jQuery
重新映射到$
using:
(function($){
...my functions here...
})(window.jQuery);
这适用于从该文件中触发的函数,但如果我在PHP中使用任何内联触发器,它们将不再起作用。 例如:
<a onclick="loadFullPost('<?=get_permalink()?>?ajax=true','<?=$post->post_name?>',<?=$post->ID?>)">Read more</a>
在重新映射之前工作正常,但现在没有。 我不能像往常一样在js文件中绑定事件,因为我无法访问我需要的PHP和WordPress函数 - 除非我遗漏了一些东西。 例如,这不起作用:
$( "#target" ).click(function() {
loadFullPost('<?=get_permalink()?>?ajax=true','<?=$post->post_name?>',<?=$post->ID?>)
});
有没有办法解决?
问题是你的函数不再是全局变量。 这是一件好事™。 (见下文了解原因。)
有没有办法解决?
到目前为止,最好的方法是不要挂钩这样的事件。 相反,保持你的代码和标记分开,并使用jQuery的挂钩的功能on
和类似。 见下文了解更多。
但是如果你觉得必须,你可以通过在window
中将它们指定为属性来使函数全局化:
(function($) {
window.loadFullPost = function() {
// ...
};
)(jQuery);
要么
(function($) {
function loadFullPost() {
// ...
}
window.loadFullPost = loadFullPost;
)(jQuery);
那你怎么办?
<a onclick="loadFullPost('<?=get_permalink()?>?ajax=true','<?=$post->post_name?>',<?=$post->ID?>)">Read more</a>
...没有使用全局函数? 像这样:
<a class="load-full-post" data-permalink="<?=get_permalink()?>" data-ajax=true data-post-name="<?=$post->post_name?>" data-post-id="<?=$post->ID?>">Read more</a>
然后为他们一个处理程序
$(document).on("click", ".load-full-post", function() {
var link = $(this);
// Use the values from link.attr("data-permalink") and such
// to do the work
});
或者,如果您想使用现有的loadFullPost
函数:
$(document).on("click", ".load-full-post", function() {
var link = $(this);
return loadFullPost(
link.attr("data-permalink"),
link.attr("data-ajax") === "true",
link.attr("data-post-name"),
+link.attr("data-post-id") // (+ converts string to number)
);
});
我应该提一下,你会让人们告诉你通过data
功能访问这些data-*
属性。 你可以这样做,但除非你使用data
的各种附加功能,否则这是不必要的开销(为数据创建jQuery的缓存等)。 data
不是 data-*
属性的访问器函数,它比它更多(也更少)。
您还可以将您的信息作为JSON传递:
<a class="load-full-post" data-postinfo="<?=htmlspecialchars(json_encode(array("permalink" => get_permalink(), "ajax" => true, "name" => $post->post_name, "id" => $post->ID))0?>">Read more</a>
(或类似的东西,我的PHP-fu很弱)
然后:
$(document).on("click", ".load-full-post", function() {
var postInfo = JSON.parse($(this).attr("data-postinfo"));
return loadFullPost(
postInfo.permalink,
postInfo.ajax,
postInfo.name,
postInfo.id
);
});
为什么让你的函数非全局化是一件好事:全局命名空间非常拥挤,特别是当你处理多个脚本和插件以及Wordpress本身时。 您创建的全局变量越多,与另一个脚本冲突的几率就越大。 通过将您的函数很好地包含在您的作用域函数中,您可以避免踩踏别人的函数/元素/任何东西,反之亦然。
您可以将机箱中的功能添加到窗口中,如下所示:
(function($){
function loadFullPost(...) {
...
}
window.loadFullPost = loadFullPost;
}).(window.jQuery);
然后你的函数将在onlick属性等中可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.