Jquery中的选中/取消选中触发事件

6

我希望根据复选框的点击/取消点击事件设置一个变量(pageselected)。

HTML代码如下:

<thead>
    <tr id="othercheckbox">
        <th width="10"><input type="checkbox" name="zip" class="all"  value="all" /></th>              
    </tr>
</thead>
    

JS文件中的代码如下:

$('#othercheckbox').click(function() {

    if($(this).is(':checked')){
        console.log("CCCCheckeddddddd");
        that.pageselected = true;
    }
    else
    {
        console.log("UNCheckeddddddd");
        that.pageselected = false;
    }
}
      

但是这并没有按照预期的行为。我做错了什么吗?

1
表格行没有选中属性。 - j08691
这是代码中声明的一个变量,被定义为var that = e.data.that;,因此我们将所有用户定义的变量称为that.<variable_name>。 - mmt
谢谢。那么我应该在哪里添加ID? - mmt
@mmt:请检查答案。 - Shivang MIttal
3个回答

13

你正在检查行是否已选中,这是不可能的。绑定onchange事件到复选框上。将其放在复选框上,比如说checkbox1。

HTML代码:

<input type="checkbox" name="zip" id="checkbox1" class="all"  value="all" />

JS 脚本:

$('#checkbox1').change(function(){

    if($(this).is(':checked')){
        console.log("CCCCheckeddddddd");
    }
    else
    {
        console.log("UNCheckeddddddd");
    }    

});

我会删除 that,因为它未定义。 - Zack

6

JSFIDDLE演示

由于复选框位于带有id为othercheckboxtr中,请使用以下代码:

$('#othercheckbox input[name="zip"]').click(function () {
    if ($(this).is(':checked')) {
        alert("CCCCheckeddddddd");
        //that.pageselected = true;
    } else {
        alert("UNCheckeddddddd");
        //that.pageselected = false;
    }
});

2

更改选择器,将事件绑定在输入框上而不是表格行上。如果您只想设置 truefalse,则以下方法会更好。

JS:

$('#othercheckbox input').click(function () {        
    var pageselected = $(this).is(':checked'); // change pageselected or any variable of your choice accordingly.
});

Demo: http://jsfiddle.net/lotusgodkk/GCu2D/329/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接