在我的WordPress主题中将jQuery重新映射到$后,我无法再从js文件外部触发函数


After remapping jQuery to $ in my WordPress theme, I can no longer trigger functions from outside the js file

我正在开发一个WordPress主题,里面有很多jQuery。默认情况下,WordPress不允许您使用$快捷方式,您必须使用完整的jQuery - 例如 jQuery('.class')而不是$('.class').

对于几行代码来说,这并不是什么麻烦,但是我现在有很多,所以我使用以下方法将jQuery重新映射到$

(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 属性等将是可见的。