【发布时间】:2014-09-28 19:07:28
【问题描述】:
我正在尝试编写一个 wordpress 小部件,但选项表单让我有些悲伤。该小部件旨在显示两个图像和每个下方的计数器,其中计数器依赖于日期。该逻辑已排序。
但是,在图像上没有计数器的情况下,我试图放置一个复选框,选中该复选框将禁用处理图像和计数器的输入字段,这样我就可以读取布尔值并输出没有计数器的更简单的图像。
我遇到的问题是,附加到复选框的 JQuery 正在禁用输入,但我无法再次单击它来启用它们,因为它只是锁定在它的边缘状态,因为复选框获得蓝色'发光',看起来没有检查。我不明白为什么代码没有按我的预期工作。值得注意的是,这是我第一次使用 JQuery,如果标准的 javascript 也可以,解决方案也不需要 JQuery。
我有两个功能相同的部分,每个图像计数器对一个。这是其中一个部分的代码:
<h3>Anime 1</h3>
<p>
<input class="check1" type="checkbox" <?php checked($instance['s1rand'], 'on'); ?> id="rand1" name="<?php echo $this->get_field_name('s1rand'); ?>" />
<label for="<?php echo $this->get_field_id('s1rand'); ?>">Label of your checkbox variable</label>
</p>
<div class="ani1">
<p>
<label for="<?php echo $this->get_field_id('s1title'); ?>"><?php _e('Anime 1 Name:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('s1title'); ?>" name="<?php echo $this->get_field_name('s1title'); ?>" type="text" value="<?php echo $s1title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('s1date'); ?>"><?php _e('Anime 1 Start Date:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('s1date'); ?>" name="<?php echo $this->get_field_name('s1date'); ?>" type="date" value="<?php echo $s1date; ?>" />
</p>
</div>
jQuery
jQuery(function($){
$(document).on('click', '#rand1', function(evt){
checked = $('#rand1').val();
$('div.ani1 :input').attr('disabled',checked);
return false;
});
});
编辑:自发布以来,我已经更改了代码,以便我现在使用 id 而不是类,但问题仍然存在,即使使用 3rror404 的解决方案
新代码:
<h3>Anime 1</h3>
<p>
<input class="check1" type="checkbox" <?php checked($instance['s1rand'], 'on'); ?> id="rand1" name="<?php echo $this->get_field_name('s1rand'); ?>" />
<label for="rand1">Label of your checkbox variable</label>
</p>
<div id="ani1">
<p>
<label for="s1title"><?php _e('Anime 1 Name:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="s1title" name="<?php echo $this->get_field_name('s1title'); ?>" type="text" value="<?php echo $s1title; ?>" />
</p>
<p>
<label for="s1date"><?php _e('Anime 1 Start Date:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="s1date" name="<?php echo $this->get_field_name('s1date'); ?>" type="date" value="<?php echo $s1date; ?>" />
</p>
</div>
jQuery
$('#rand1').on('change',function() {
var isChecked = $(this).prop('checked'); // this will equate to either 'true' or 'false'...
alert(isChecked); //this line doesn't work, which makes me think this function isn't working
$('#ani1 input').attr('disabled',isChecked); // ...meaning that we can use its value to set the 'disabled' attribute
});
我根据以下语句运行JQuery 1.11.1版本:
alert(jQuery.fn.jquery);
【问题讨论】:
-
如果
alert(isChecked);不起作用,则不会触发更改事件。你确定rand1是正确的ID吗?如果您将alert($('#rand1').length)添加到您的文档就绪块,会收到什么警报? -
我确定这是正确的 ID。 alert($('#rand1').length) 输出 1 - 这在上下文中意味着什么,因为我想不出复选框的长度是多少。
-
length 是指选择器返回的元素数组的大小。所以元素肯定存在。您是否将上述代码包装在 jquery“文档就绪”块中?
-
假设 jQuery(function ($) { code } 是一个文档就绪块,是的
标签: javascript jquery html wordpress checkbox