본문 바로가기

JavaScript/jQuery

[jQuery] data() 알아보기

jQuery 소스를 보다 보면 data()라는 함수가 자주 등장하거나 아예 없을 때도 있다.

제대로 쓰는 사람이 있고 아예 안 쓰는 사람이 있는 것 같다.

뭐길래 호불호가 갈리는걸까? 알아보자!

 

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

 

가장 기초적인 공식 홈페이지의 .data() 정의를 알아봤다.

대충 정리하면 요소에 임의 데이터를 저장하거나 데이터를 불러올 수 있다는 것이다.

.data( key, value )

Description: Store arbitrary data associated with the matched elements.

 

일치하는 요소에 연결된 임의 데이터를 저장한다.

key는 string이고, value는 undefined를 제외한 모든 자바스크립트 유형이 들어갈 수 있다.

 

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

 

안전한 방식으로 모든 유형의 데이터를 DOM 요소에 첨부할 수 있다고 한다.

 

$("div").data("stringData", "abcd");
$("div").data("numberData", 1234);
$("div").data("objectData", {a:"1", b:"2"});
$("div").data("functionData", function(){});

.data( key )

Description: Return arbitrary data associated with the first element in the jQuery collection, as set by data() or by an HTML5 data-* attribute.

 

data()로 설정된 데이터 혹은 data-*로 설정된 데이터를 가져올 수 있다.

key는 저장된 데이터 이름이고, 매개변수 없이 호출하면 각 저장된 값을 속성으로 포함하는 JavaScript 객체가 반환된다.

 

The .data() method allows us to read data previously associated with DOM elements. We can retrieve several distinct values for a single element one at a time, or as a set:

 

data()를 통해서 DOM 요소와 연관된 데이터를 읽을 수 있다고 한다.

 

 

 


 

스크립트 영역이 아닌 HTML 속성에 data-* 항목으로 사용자 임의 데이터 속성을 추가할 수도 있다.

 

<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

 

 

 

간단히 data()의 사용방법에 대해 알아봤다.

모든 유형의 데이터를 DOM 요소에 저장하고 불러올 수 있으니 활용방법은 다양하다.

data-* 를 활용해 정해진 key값으로 공통 함수와 값을 주고받아서 공통적인 기능을 만들 수 있을 것 같다.

 

<div data-ars-auth
     data-ars-code="A00">
</div>

 

var arsAuth = $("div").data("arsAuth");
var arsCode = $("div").data("arsCode");

if(arsAuth != undefined) {
    // make HTML
    var _html = '<div>...</div>';
    $("div").append(_html);
    
    // run script
    if(arsCode == "A00") {
        // ...
    }
    
}

 

공통 소스에서 data-arsAuth를 체크해서 공통 인증 html을 만들어서 화면에 보여준다.

data-arsCode 값도 받아와서 특정 분기 처리도 공통 소스에서 가능할 것이다.

 

간단한 예시로 data()의 활용법도 찾아봤다.

그 외에도 다양한 방법이 있을 거고 앞으로는 상황에 맞게 잘 사용해봐야겠다.