【问题标题】:How to disable some checkboxes with jQuery如何使用 jQuery 禁用某些复选框
【发布时间】:2014-02-06 21:19:37
【问题描述】:

我正在尝试遍历一个包含一些复选框的字段,并根据数组中的数据禁用一些复选框。

对于每个框,我想检查复选框的值是否在来自 php.ini 的变量数组中找到。如果是,则禁用该复选框并将一个类添加到父级。

为什么这段代码不起作用? 这是我自己用 jQuery 编写的第一个函数,请见谅。

jQuery(function($) { // wordpress no-conflict hack

    var booked = php echo $booked_24; // the php echo syntax is wrong here, 
                but the editor does not allow me to put in proper php tags.

    $('div#acf-booking_times_24 input:checkbox').each(function() {
        if ($.inArray(this.value, booked) !== -1) {
            $(this).attr('disabled',true);
            $(this).parent('label').addClass('unavailable');
        }
    });
});

【问题讨论】:

  • 使用 .prop() 代替 .attr()
  • 在调试器中检查是否进入“if”语句

标签: jquery wordpress checkbox


【解决方案1】:

尝试替换下面的代码片段 替换你的

  $(this).attr('disabled',true);

通过

$(this).attr('disabled', 'disabled');

【讨论】:

  • 不,它的工作方式不同(对于某些浏览器)如果您使用 Prop 代替 attr 然后使用 'disabled',否则为 attr 'disabled'、'disabled' 或尝试在其他浏览器中运行
  • attr('disabled', true) 如果我在没有迭代的情况下针对整个 div 工作,所以我认为问题出在 if 语句的某个地方。
【解决方案2】:

所以我发现了错误,它非常简单。

if ($.inArray($(this).value, booked) !== -1) 

应该是

 if ($.inArray($(this).val(), booked) !== -1) 

感谢 Nicolai 的小提琴,它帮助我找到了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 2015-08-29
    • 1970-01-01
    • 2013-04-19
    • 2018-01-16
    • 2020-01-28
    • 1970-01-01
    相关资源
    最近更新 更多