如何在加载脚本时选中 jquery 中的框时更改背景

How to change a background when checking a box in jquery when a script loads

我的代码有问题。它是 Advanced Custom Fields 块中的一个复选框,可以更改背景颜色。当您单击复选框时,它不会更改颜色。我知道 ACF 块必须使用 $(document).on('change', function (),而且除了单击复选框外,我还可以执行其他有效的功能。

我的代码:

jQuery(document).ready(function ($) {
   $(document).on('change', function () {
      if ($("input#acf-block_60160a1a4dc32-field_5f8cf27e7c048-two_img_left_set_featured_img").is(':checked')) {
        $(".acf-field-5f8cf27e7c048").css({'background':'black'});
      } else {
        $(".acf-field-5f8cf27e7c048").css({'background':'white'});
      }
   });
});

@Gregory 单选按钮是实现此目的的正确方法。以下是单选框和复选框的两种方式。

带有单选按钮,例如下面是您的html。

<input type="radio" class="myclass" value="colorwhite" name="mycolor">white
<br>
<input type="radio" class="myclass" value="colorblack" name="mycolor" checked="checked">black

下面是您的 javascript 代码

<script>
jQuery(document).on('click', '.myclass', function(e){
var radioValue = jQuery("input[name='mycolor']:checked").val();
if(radioValue){
console.log('radioValue ' + radioValue);
}

if(radioValue =="colorwhite")
{
jQuery(".acf-field-5f8cf27e7c048").css({"background-color": "white"});
}

if(radioValue =="colorblack")
{
jQuery(".acf-field-5f8cf27e7c048").css({"background-color": "black"});
}


});
</script>

通过复选框。下面是实现它的例子。

<input type="radio" class="myclass" value="colorwhite" name="mycolor">white
    <br>
    <input type="radio" class="myclass" value="colorblack" name="mycolor" checked="checked">black

<script>
    jQuery(document).on('click', '.myclass', function(e){
    var selected_color = jQuery("input[name='mycolor']:checked").val();
    if(selected_color){
    //console.log('radioValue ' + selected_color);
    }

    if(selected_color =="colorwhite")
    {
        console.log(selected_color);
    jQuery(".acf-field-5f8cf27e7c048").css({"background-color": "white"});
    }

    if(selected_color =="colorblack")
    {
        console.log(selected_color);
        jQuery(".acf-field-5f8cf27e7c048").css({"background-color": "black"});
    }


    });
    </script>

不能说我对 wordpress 有任何经验,但从一般观点来看,对整个文档使用一个 change 侦听器可能会产生意想不到的后果,因为任何触发更改(其他输入,选择、文本区域等)将 运行 此代码。您是否尝试过使用 .on() method 提供选择器参数以更好地确定此处理程序的范围?

$(document).on(`change`, `input#acf-block_60160a1a4dc32-field_5f8cf27e7c048-two_img_left_set_featured_img`, function () {
  $(`.acf-field-5f8cf27e7c048`).css(`background`, $(this).is(`:checked`) ? `black` : `white`);
});