jq attr与prop

  • attr 表示HTML文档节点属性
  • prop表示JS对象属性 (jquery版本1.6+)

区别:在1.6版本前,attr()获取的是初始化值,除非通过attr(‘name’,’value’)改变,但是这个方法可能导致不一致的行为;在1.6版本开始prop()获取属性值是动态的,比如checkbox,选中后,checked变为true,prop值也会发生改变。

$("input").prop("disabled", false);//设置disable 为false
if ($("input").prop("disabled")) {
    //do something
    alert("disabled is :true");
} else {
    //do something
    alert("disabled is :false");
}

$("input").prop("checked", true);
if ($("input").prop("checked")) {
    //do something
    alert("disabled is :true");
} else {
    //do something
    alert("disabled is :false");
}

官方提供的资料:

elem.checked true (Boolean) Will change with checkbox state
$( elem ).prop( "checked" ) true (Boolean) Will change with checkbox state
elem.getAttribute( "checked" ) "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6) "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6.1+) "checked" (String) Will change with checkbox state
$( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>prop demo</title>
    <style>
        p {
            margin: 20px 0 0;
            }
        b {
            color: blue;
            }
    </style>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
<p></p>
<script>
    $( "input" ).change(function() {
        var $input = $( this );
        $( "p" ).html(
                ".attr( \"checked\" ): <b>" + $input.attr( "checked" ) + "</b><br>" +
                ".prop( \"checked\" ): <b>" + $input.prop( "checked" ) + "</b><br>" +
                ".is( \":checked\" ): <b>" + $input.is( ":checked" ) + "</b>" );
    }).change();
</script>
</body>
</html>

猜你喜欢

转载自my.oschina.net/u/2608562/blog/1820074