티스토리 뷰

HTML 태그 안에서 사용자 데이타 저장하기
Web Technologies

태그 속성과 스크립트의 잘못된 사용의 예
속성의 잘못된 사용
 
<img class="pic-0" />
<img class="pic-1" />
<img class="pic-2" />

 
for(var i = 0; i < $("img").length; i++) {
   $(".pic-" + i).doStuff(); // Do something   
}

스크립트의 잘못된 사용
 
<p>
   This is the actual text
   <span>This is the tooltip</span>
</p>

 
$("p span").hide();
$("p").hover(function() {
   $("span", this).show();
});


JavaScript 의 해결책
the .data() API 를 사용하는 DOM 구조를 사용한다.  
 
<img />
<img />
<img />

 
var i = 0;
$("img").each(function(){
   $(this).data("iterator", i); // Store data
   i++;
});
 
$("img").hover(function(){
   alert($(this).data("iterator")); // Retrieve data
});

HTML5 의 custom data attributes 사용하기 
HTML 안에 속성처럼 데이타를 저장하거나 추가할 수 있다.  
data- 로 시작되는 속성을 사용한다. 
<img data-index="0" />
<img data-index="1" />
<img data-index="2" />
 
<p data-tooltip="This is the tooltip">
   This is the actual text
</p>
jQuery 의 .attr() 메소드를 사용하여 값을 가져올 수 있다.

   var index = $("img").attr("data-index");
   var tooltip = $("p").attr("data-tooltip");

속성값이 유일하다면 얼마든지 추가될 수 있다.

<img alt="My alt text"
   data-longdescr="My long description"
   data-geo="Location I took the picture"
   data-cam="The type of camera I used"
   data-time="The time I took the picture" />


참고자료 
HTML5 data-* attributes are great and you know it
댓글