jQuery之css以及attr與prop的區別

文章目錄

CSS

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>溫故而知“心”</title>
    <style>

    </style>
</head>

<body>
    <div class="demo"></div>
</body>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    //給div添加行內樣式(賦值)
    $('.demo')
        .css({ width: '100px', height: '100', backgroundColor: '#ff0000' })
        .css({ width: 300 })//可以鏈式調用

    //取值
    console.log($('.demo').css("width"))
    console.log($('.demo').css("backgroundColor"))
</script>

</html>

attr

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>溫故而知“心”</title>
    <style>

    </style>
</head>

<body>
    <div class="demo" xyz="aa"></div>
    <input type="checkbox" checked=''>
</body>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    /*
      attr 基於 setAttribue getAttribue
      運用場景:如果你想自定義屬性值的時候就使用attr
    */
    //取值
    console.log($('.demo').attr('class'))
    console.log($('.demo').attr('xyz'))

    //賦值
    $('.demo').attr('id', 'lm')
    /*
      selected checked disabled
  
      拿checked屬性來說,不管你checked的屬性值填寫的是什麼,
      attr都給你返回checked
  
      所以:在處理這類屬性的時候不推薦使用attr來處理,而使用prop
    */
    console.log($('input').attr('checked'))


</script>

</html>

prop

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>溫故而知“心”</title>
    <style>

    </style>
</head>

<body>
    <div class="demo" xyz="aa"></div>
    <input type="checkbox" checked=''>
</body>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    /*
     prop:特性映射、非特性不能映射。
     class屬性可以取到值,而自己定義的屬性取不到值。
    */
    //取值
    console.log($('.demo').prop('class'))
    console.log($('.demo').prop('xyz'))
    /*
        prop關注的是checked的狀態,如果input標籤被選中,
        那麼$('input').prop('checked')將返回true,還有
        一點就是隻要被選中,不管你checked屬性值裏面寫的是什麼
        都會返回true,但是你如果把checked屬性值刪除掉,那麼將
        返回false
    */
    console.log($('input').prop('checked'))

    //賦值
    $('div').prop('id', 'lm')


</script>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章