注意输入的更改[type ="checkbox"]

Ila*_*sda 13 jquery

如何在复选框更改时运行函数?

我正在尝试编写小复选框替换函数 - 但我做错了.

码:

(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();

    });

});
Run Code Online (Sandbox Code Playgroud)

PlayGround:现场演示

Jon*_*Jon 16

这是你想要的吗?我的印象是你的事情过于复杂.

$('input[type="checkbox"]').change(function() {
    alert ("The element with id " + this.id + " changed.");
});
Run Code Online (Sandbox Code Playgroud)

  • @jAndy:复制/粘贴也可以.:) (3认同)
  • `input:checkbox`选择器就可以了 (2认同)

Fel*_*ing 11

你的脚本中有一些拼写错误和错误.

if($('.checbox').prop('checked', false) === true)
//         ^                   ^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

应该

if(this.prop('checked'))
Run Code Online (Sandbox Code Playgroud)

if($('.checkbox').prop('checked'))当然也会工作,但为什么再次选择元素,如果你已经把它作为一个插件并且元素可以通过this

$('.checbox').bind('change', function(){
//      ^
Run Code Online (Sandbox Code Playgroud)

应该

$('.checkbox').bind('change', function(){
//      ^
Run Code Online (Sandbox Code Playgroud)

工作演示:http://jsfiddle.net/fkling/yGBAK/40/

也就是说,添加和删除类比更改元素的ID更好(更合乎逻辑).


Yon*_*Ran 9

$('.checkbox').change(function(){
    alert('changed');
})
Run Code Online (Sandbox Code Playgroud)

我使用了你在复选框(.checkbox)上放置的类.它检测复选框状态的变化(这也适用于其他输入)

示例中包含单击或未单击复选框的警报"已更改".

如果您想知道每次是否检查:

$('.checkbox').change(function(){
    if($(this).is(':checked')){
        alert('checked');
    } else {
        alert('not checked');
    }
});
Run Code Online (Sandbox Code Playgroud)