选中所有复选框,选中另一个复选框使用jquery [英] check uncheck All checkboxes with another single checkbox use jquery

查看:149
本文介绍了选中所有复选框,选中另一个复选框使用jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jquery-1.9.1.js
在我的html页面,它第一次工作。

I use jquery-1.9.1.js In my html page, it works well for the first time.

就像http://jsfiddle.net/pzCcE/1/

有人可以帮我以改善它?

Can somebody help me to improve it?

<table id="tab1">
    <input type="checkbox" name="checkAll" id="checkAll">全選
    <input type="checkbox" name="book" id="book" value="book1">book1
    <input type="checkbox" name="book" id="book" value="book2">book2
    <input type="checkbox" name="book" id="book" value="book3">book3
    <input type="checkbox" name="book" id="book" value="book4">book4
    <input type="checkbox" name="book" id="book" value="book5">book5</table>

$(function () {
    $("#tab1 #checkAll").click(function () {
        if ($("#tab1 #checkAll").is(':checked')) {
            $("#tab1 input[type=checkbox]").each(function () {
                $(this).attr("checked", true);
            });

        } else {
            $("#tab1 input[type=checkbox]").each(function () {
                $(this).attr("checked", false);
            });
        }
    });
});


推荐答案

更改

$(this).attr("checked", true);

$(this).prop("checked", true);

jsFiddle示例

jsFiddle example

我实际上刚刚回答了另一个类似的问题。根据 .prop()文档:

I actually just answered another question that was similar to this. Per the .prop() docs:


.prop()方法是设置
属性值的一种方便方法,特别是在设置多个属性时,使用函数返回的值
,或者在$ b上设置多个元素的值$ b一次。应该在设置selectedIndex,tagName,nodeName,
nodeType,ownerDocument,defaultChecked或defaultSelected时使用。由于
jQuery 1.6,这些属性不能再使用.attr()
方法设置。它们没有相应的属性,只有
属性。

The .prop() method is a convenient way to set the value of properties—especially when setting multiple properties, using values returned by a function, or setting values on multiple elements at once. It should be used when setting selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, or defaultSelected. Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.

属性通常影响DOM元素的动态状态,而没有
更改序列化的HTML属性。示例包括输入元素的值
属性,输入的disabled属性和
按钮或复选框的checked属性。 .prop()方法
应该用于设置disabled和checked而不是.attr()
方法。
.val()方法应该用于获取和设置
值。

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.

这篇关于选中所有复选框,选中另一个复选框使用jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆