在 Wordpress 中定义 jQuery 函数

Defining a jQuery function in Wordpress

我想我写了一个应该是working/loading但不是的函数。我在一个基于 WordPress 的网站上工作,所以我不知道我定义函数的方式是否不适用于 word press,或者是否还有其他问题。

我在外部文件中的JavaScript是

jQuery.fn.tapFilter = function(action) {
    if (action === "hide") {
        jQuery(this).addClass('tap-hidden');
        jQuery('.ptb_list-post:not(:has(article:not(.tap-hidden)))').parent('.tap-subcategory').addClass('tap-hidden');
        return this;
    }
    if (action === "show") {
        jQuery(this).removeClass('tap-hidden');
        jQuery('.ptb_list-post:has(article:not(.tap-hidden))').parent('.tap-subcategory').removeClass('tap-hidden');
        return this;
    }
};

我认为这是有道理的。我更像是一个涉足编程的设计师。我知道必须使用 jQuery 而不是 WordPress 中的 $。

我正在尝试通过在页面上调用它来检查函数是否存在

jQuery(document).ready(function( $ ) {
  if (typeof tapFilter == 'function') {
    alert("Function Exists" );
  }
});

有问题的页面是 http://truthaboutporn.org/all-research

我不确定为什么它一开始没有加载,但在重写函数声明的方式时,我加载了它并 运行 在页面上。

function(a) {
  a.fn.tapFilter = function(x) {
    if (x === "hide") {
      jQuery(this).addClass('tap-hidden');
      jQuery('.ptb_list-post:not(:has(article:not(.tap-hidden)))').parents('.tap-subcategory').addClass('tap-hidden');
      return this;
    }
    if (x === "show") {
      jQuery(this).removeClass('tap-hidden');
      jQuery('.ptb_list-post:has(article:not(.tap-hidden))').parents('.tap-subcategory').removeClass('tap-hidden');
      return this;
    }
  };
})(jQuery);

我遇到的另一个最大问题是理解 .parent().parents() 之间的区别。我不得不在 DOM 树上走得更远,我意识到我没有 post 这里的 html 片段对这个问题有帮助。

隐藏父元素的脚本基于这个问题: select parent node if all children have assigned class