1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<script src="js/jquery.js"></script>
</head>
<body>
 
    <div id="d1" data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>    
 
    <script>
 
        // attr는 html 마크업 속성(Attribute)으로 접근
        // data는 dom객체 속성(Property)으로 접근
 
        // attr 메서드 값을 가져오면 String 타입이다.
        console.log($("#d1").attr("data-role"));        // String "page"
        console.log($("#d1").attr("data-last-value"));  // String "43"
        console.log($("#d1").attr("data-hidden"));     // String "true"
        console.log($("#d1").attr("data-options"));     // String '{"name":"John"}'
        
        
        // html5 data 속성은 jquery객체의 data메서드로 핸들링이 가능하다.
        // data메서드로 값을 가져오면 실제 자료형으로 적용된다.
        console.log($("#d1").data());               // Object
        console.log($("#d1").data("role"));          // String "page"
        console.log($("#d1").data("lastValue"));     // Number 43
        console.log($("#d1").data("hidden"));       // boolean true
        console.log($("#d1").data("options").name); // String "John"  //객체로 접근
 
    </script>      
 
</body>
</html>


<div id="box" data-columns="3" data-index-number="12314" data-parent="cars"></div>

<script type="text/javascript">
    
    // dataset은 IE 11 미만에서는 지원하지 않는다. 
    // data 속성 값을 다루기 위해서는 일반 속성에 접근하기 위한 함수 getAttribute()와 setAttribute() 함수를 사용해야 한다.    
    var box = document.getElementById('box').dataset;
    console.log(box); // DOMStringMap {columns: "3", indexNumber: "12314", parent: "cars"}

    box.columns // "3"
    box.indexNumber // "12314"
    box.parent // "cars"

</script>


반응형
Posted by 힘없는염소