如何在 WordPress 管理员上运行 jQuery 代码?

问题描述

如何在创建新帖子时运行 jQuery 脚本。我能够将脚本排入队列,并且可以在编辑器中看到 .js 文件,但代码不会执行。我知道有一种特殊的方式可以在管理员中运行 jquery 代码,但找不到这种方式。该代码一个简单的脚本,用于在单击时更改使用 ACF 的按钮的背景。我能够让它在 codepen 上工作 - https://codepen.io/openbayou/pen/MWjOOZM

代码如下:

<div class="acf-field acf-field-button-group acf-field-5fe2d3efcb5f8" data-name="Box_photo_deets" data-type="button_group" data-key="field_5fe2d3efcb5f8" data-conditions="[[{&quot;field&quot;:&quot;field_5f8bec0f9f45d&quot;,&quot;operator&quot;:&quot;!=empty&quot;}]]">
   <div class="acf-label"></div>
   <div class="acf-input">
      <input type="hidden" name="acf-block_5fe163b63d274[field_5fe2d3efcb5f8]">
      <div class="acf-button-group"><label class="selected"><input type="radio" name="acf-block_5fe163b63d274[field_5fe2d3efcb5f8]" value="Box_show_deets" checked="checked"> Show details</label></div></div>
</div>

脚本如下:

(function ($) {
$(window).on('my.custom.event',function () {
    $(".acf-field-5fe2d3efcb5f8 .acf-input .acf-button-group label").click(function(){
        $(".acf-field-5fe2d3efcb5f8 .acf-input .acf-button-group label.selected").css('background','black');
    });
});
})(jQuery);

jQuery(window).trigger('my.custom.event');

解决方法

在逻辑之前让 DOM 准备好。

(function($) {
    $(document).ready(function() {

       $(".acf-field-5fe2d3efcb5f8 .acf-input .acf-button-group label")
       .click(function() {
           $(".acf-field-5fe2d3efcb5f8 .acf-input .acf-button-group label.selected")
           .css('background','black');
       });
    });
})(jQuery);