• JQuery属性操作之attr()和prop()的区别


    代码示例:

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>attr() 和 prop()区别</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(function () {
                //获取第一个input
                var input_first = $("input").first();
                //undefined 因为attr是获取的这个对象属性节点的值, 而词视没有这个属性节点, 所以输出undefined
                console.log(input_first.attr("style"));
                //输出CSSStyleDeclaration对象, 对于一个DOM对象, 是具有原生的style对象属性的,所以输出了style对象 
                console.log(input_first.prop("style"));
                console.log(document.getElementById("test1").style);
    
                $("button").click(function () {
                    alert(input_first.prop("checked")? "男": "女");
                })
            })
        </script>
    </head>
    <body>
        <input type="radio" id="test1" name="sex" checked><input type="radio" id="test2" name="sex"><button>提交</button>
    </body>
    </html>

    什么时候使用attr(), 什么时候使用prop()?

    (1). 当只有true或者false时, 使用prop();

    (2). 其他则使用attr()

  • 相关阅读:
    [IOI2013]Dreaming
    Lost Cows
    Mobile Service
    [POI2005]Bank notes
    [CTSC2007]动物园zoo
    [CF1093F]Vasya and Array
    [雅礼集训 2017 Day1]市场
    [APIO2014]序列分割
    [CEOI2004]锯木厂选址
    [APIO2010]特别行动队
  • 原文地址:https://www.cnblogs.com/yang-wei/p/9507288.html
Copyright © 2020-2023  润新知