본문 바로가기

Web Application/jQuery

07.10 - jQuery Reference - .attr()

Original Reference : http://api.jquery.com/attr/

Contents:
 attr( attributeName )
  .attr( attributeName )
 attr( attributeName, value )
  .attr( attributeName, value )
  .attr( map )
  .attr( attributeName, function(index, attr) )

.attr( attributeName ) / Returns : String

설명 : 일치하는 요소에 대하여 지정된 요소에 대한 속성의 값을 가져옵니다.

.attr (attributeName) - 추가된 버젼 1.0

attributeName 얻으려는 특성의 이름입니다.

중요. .attr() 메서드는 일치하는 요소들 중에서 첫번째 요소의 특성만을 가져옵니다. 각 요소에 대한 개별적인 값을 가져오기 위해서는 jQuery의 .each() 또는 .map() 메서드와 같은 루핑 구문을 이용하여야 합니다.

jQuery의 .attr() 메서드의 이용시에는 다음과 같은 두 가지 주요 장점이 있습니다.

  1. 편의성 : jQuery 개체를 직접적으로 호출하거나 다른 jQuery 와 연결할 수 잇습니다.
  2. 크로스-브라우저 호환성 : Some attributes have inconsistent naming from browser to browser. Furthermore, the values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.

만일, 설정되지 않은 특성 값을 가져오려고 할 경우 .attr() 메서드는 undefined 를 반환합니다.

Example:
페이지에서 첫번째 <em> 의 title 특성을 찾아옵니다.
<!DOCTYPE html>
<html>
<head>
  <style>em { color:blue; font-weight;bold; }
  div { color:red; }</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>
    Once there was a <em title="huge, gigantic">large</em> dinosaur...
  </p>

  The title of the emphasis is:<div></div>
<script>var title = $("em").attr("title");
    $("div").text(title);
</script>
</body>
</html>

 
.attr ( attributeName, value ) / Returns : jQuery

설명 : 일치하는 요소에 대하여 하나 또는 그 이상의 특성을 설정합니다.

.attr( attributeName, value ) - 추가된 버젼 1.0

attibuteName 설정하고자 하는 특성의 이름.
value 특성에 설정할 값.

.attr( map ) - 추가된 버젼 1.0

map 설정하고자 하는 특성 값의 map.

.attr( attributeName, function(index, attr) ) - 추가된 버젼 1.1

attributeName 설정하고자 하는 특성의 이름.
function(index, attr) A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.

.attr() 메서드는 특정한 특성 값을 설정할 수 있는 간단하고도 강력한 방법입니다. 특히 여러 특성값에 대해서나 함수의 반환 값을 이용한 설정이 가능합니다. 다음의 이미지를 살펴봅시다.
<img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />

Setting a simple attribute
우리는 .attr() 메서드에 이름과 특성을 전달하는 것으로서 간단하게 alt 특성을 변경할 수 있습니다.:
$('#greatphoto').attr('alt', 'Beijing Brush Seller');
우리는 다음과 같은 방법을 통해 특성값을 추가할 수도 있습니다.:
$('#greatphoto')
  .attr('title', 'Photo by Kelly Clark');

Setting several attributes at once
alt 특성을 변경하는 동시에 title 특성을 추가하기 위해 우리는 두가지의 이름과 값들을 map(JavaScript object literal)을 이용하여 메소드에 전달할 수 있습니다. 각각의 키와 값이라는 쌍을 특성 맵에 추가하거나 수정할 수 있습니다.: 
$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

여러 속성을 설정하는 경우 특성이나 이름에 대한 따옴표는 선택사항입니다.
WARNING '클래스' 특성을 설정할때는 항상 따옴표를 사용해야 합니다!


Computed attribute values
함수를 사용하여 특성을 설정 하는 경우, 우리는 다른 요소의 속성을 기준으로 값을 계산할 수 있습니다. 예를 들어, 우리는 기존의 값을 새로운 값으로 연결할 수 잇습니다.:
$('#greatphoto').attr('title', function() {
  return this.alt + ' - photo by Kelly Clark'
});

한 번에 여러 요소의 특성의 수정이 필요할 경우, 이러한 계산 함수는 유용하게 사용될 수 있습니다.


Examples:
Example : 페이지 내의 모든 <img>들의 특성 설정.
<!DOCTYPE html>
<html>
<head>
  <style>
  img { padding:10px; }
  div { color:red; font-size:24px; }</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <img />
  <img />
  <img />

  <div><B>Attribute of Ajax</B></div>
  <script>$("img").attr({ 
          src: "/images/hat.gif",
          title: "jQuery",
          alt: "jQuery Logo"
        });
    $("div").text($("img").attr("alt"));</script>
</body>
</html>

Example : 1번째 보다 큰 단추를 비활성화.
<!DOCTYPE html>
<html>
<head>
  <style>button { margin:10px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <button>0th Button</button>
  <button>1st Button</button>
  <button>2nd Button</button>
  <script>$("button:gt(1)").attr("disabled","disabled");</script>
</body>
</html>

Example : 페이지의 div 들의 정렬기준으로 id 설정.
<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  span { color:red; }
  b { font-weight:bolder; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <div>Zero-th <span></span></div>
  <div>First <span></span></div>
  <div>Second <span></span></div>
  <script>$("div").attr("id", function (arr) {
          return "div-id" + arr;
        })
        .each(function () {
          $("span", this).html("(ID = '<b>" + this.id + "</b>')");
        });</script>
</body>
</html>

Example : 이미지의 title 특성을 바탕으로 src 특성 설정하기.
<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <img title="hat.gif"/>
  <script>$("img").attr("src", function() { 
          return "/images/" + this.title; 
        });
</script>
</body>
</html>
 
2010.07.10 - 레퍼런스 일부 번역
2010.07.10 / 레퍼런스 번역 & 정리 - by Kinesis(김 해광)
- 불법적인 펌이나 스크랩, 편집, 재유포를 금지합니다.
- 필요하다면 이 페이지로 접근할 수 있는 링크를 남겨주세요.

 

'Web Application > jQuery' 카테고리의 다른 글

07.10 - jQuery Reference - .addClass()  (0) 2010.07.10
07.10 - jQuery Reference - Attributes  (0) 2010.07.10