注意输入的更改[type =" checkbox"] [英] Watch for change of the input[type="checkbox"]
问题描述
如何在复选框更改时运行功能?
How can I run a function on checkbox change?
我正在尝试以此为基础编写小的复选框替换功能-但我做错了事.
I'm trying to write small checkbox replacing function base on that - but I'm doing something wrong.
代码:
(function($) {
$.fn.checking = function() {
if ($('.checbox').prop('checked', false) === true) {
$('.new-checkbox').prop('id', 'unchecked');
} else {
$('.new-checkbox').prop('id', 'checked');
}
};
})(jQuery);
$(document).ready(function() {
$('.checkbox').wrap('<div class="checkbox-wrapper"></div>');
$('.checkbox-wrapper').append('<p class="new-checkbox">Blue = Checked, Red = Unchecked</p>');
$('.checkbox').checking();
$('.checbox').bind('change', function() {
$(this).checking();
});
});
PlayGround:实时演示
PlayGround: LIVE DEMO
推荐答案
您的脚本中有一些错别字和错误.
You have some typos and errors in your script.
if($('.checbox').prop('checked', false) === true)
// ^ ^^^^^^^^^^^^^^^^^
应该是
if(this.prop('checked'))
if($('.checkbox').prop('checked'))
当然也可以,但是为什么要再次选择该元素(如果您已经将其作为插件并且可以通过this
来使用)呢?
if($('.checkbox').prop('checked'))
would work too of course, but why select the element again, if you already made it a plugin and the element is available via this
?
还有
$('.checbox').bind('change', function(){
// ^
应该是
$('.checkbox').bind('change', function(){
// ^
正在运行的演示: http://jsfiddle.net/fkling/yGBAK/40/
也就是说,添加和删除类比更改元素的ID更好(更合逻辑).
That said, it is better (more logical) to add and remove a class than changing the ID of the element.
这篇关于注意输入的更改[type =" checkbox"]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!