zoukankan      html  css  js  c++  java
  • jquery 获取checkbox的checked属性总是undefined

    项目中用的jquery1.9 今天需要检测一个checkbox的选中状态,想当然的用 .attr("checked") ,结果发现,无论是否选中,这个值都是 undefined 未定义。

    折腾了半天,无奈,只能取jq官网看看文档,发现有这么一段说明

    As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop()method.

    注意最后两句话,说什么.attr() 不能用于普通对象,数组,窗口,文档什么玩意的,要重新获取改变dom属性,用.prop()方法。

    ok,虽然不太明白它说的具体含义是什么,但是看到.prop方法姑且一试吧,结果还真可以,若选中则返回true否则返回false。

    代码贴上来,有兴趣可自行测试:

    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
            <script>
                $(function(){
                    $("#clk").click(function(){
                        alert($("#ckb").prop("checked"));
                    })
                })
            </script>
        </head>
        <body>
            <input type="button" value="click" id="clk">
            <input type="checkbox" id="ckb"/>
        </body>
    </html>
    
  • 相关阅读:
    【转】Centos yum 换源
    centos7下使用yum安装mysql
    【转】简易smtp调用类
    【转】Beanstalkd 队列简易使用
    【转】mysql 拖库写库用法
    【转】scp 命令格式
    【转】mac os 安装php
    pip 国内源 gem 国内源
    【转】25个必须记住的SSH命令
    NHibernate 有好几种数据库查询方式
  • 原文地址:https://www.cnblogs.com/jsonzheng/p/3655874.html
Copyright © 2011-2022 走看看