jQuery Api 정리 2

# Work/└ jQuery 2012. 4. 26. 09:26 |
반응형

## .addClass(className)

className 특정 조건에 추가할 하나 이상의 클래스 명

 

.addClass( function(index, class))

function(index, class) 함수에서 반환된 하나 또는 띄어쓰기로 구분된 그 이상의 클래스를 추가할 수 있습니다.

 

이 함수는 .removeClass()와 자주 같이 사용됨.

만약 클래스의 바꿔치기를 원하시면 이 두가지 함수를 아래와 같이 사용.

 

   myClass 와 noClass를 없앤 후에 yourClass 를 추가하는 구문

$('p').removeClass('myClass noClass').addClass('yourClass');  

  

   * 만일 5개의 li 가 존재한다면 이 함수는 "item-4"라는 클래스명을 반환해 줌.

$('ul li:last').addClass(function() {
  return 'item-' + $(this).index();
});

 

 ## .attr(attributeName)

인자에 따라 2가지로 사용할 수 있다.

하나의 인자만 있다면 속성값을 가져오는 것이고 2개의 인자를 쓰면 속성값을 요소에 부여하는 것.

 

1. attr( attributeName )

.attr( attributeName )

 

2. attr( attributeName, value )

.attr( attributeName, value ) - 속성명, 속성값

.attr( map ) - map 속성명과 속성값이 쌍을 이루는 집합(map)

.attr( attributeName, function(index, attr) ) - function(index, attr) 속성값을 반환하는 함수. this 키워드는 현재의 요소. 요소 집합의 인덱스 위치와 이전 속성값이 인자이다.

 

- 선택자에 의해 선택된 요소들 중에서 제일 처음 요소의 속성값을 가지고 오는 함수.

만일 모든 요소들의 속성값을 개별적으로 알고 싶다면, jQuery의 .each()함수나 .map() 함수를 사용.

 

예시문) 
<img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />

 

// $('#greatphoto').attr('title', 'Photo by Kelly Clark'); 하나의 속성 세팅하기

 

// $('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
}); 여러개의 속성 한번에 셋팅하기

 

// 기존의 alt 속성에 새로운 문자를 덧붙여서 속성값을 만들어 냄

$('#greatphoto').attr('title', function() {
  return this.alt + ' - photo by Kelly Clark'
});

 

 *** Internet Explorer 는 input 이나 button 요소의 type 속성을 바꾸지 못합니다.

 

  * 페이지의 모든 img 태그에 속성값들을 부여

$("img").attr({
  src: "/images/hat.gif",
  title: "jQuery",
  alt: "jQuery Logo"
});
$("div").text($("img").attr("alt")); // img의 alt 값 출력

 
* 색인이 1보다 큰 button 요소에 사용불가(disabled) 속성을 부여.

$("button:gt(1)").attr("disabled","disabled");

 

* div 요소들을 찾아서 그 색인값을 알아내고 그 값을 이용하여 div의 id 속성을 만들어 내고, span 태그에 div 의 id값을 찍어줌.

<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>

 

* img 태그의 title 요소값을 이미지의 경로값(src)로 사용

<img title="hat.gif"/>

 

<script>
$("img").attr("src", function() {
    return "/images/" + this.title;
});
</script>

 

## .hasClass(className)

.hasClass() 함수는 클래스명이 일치하는 것이 있을 경우 true를 반환함.

<script>
$("div#result1").append($("p:first").hasClass("selected").toString());

</script>

- append 함수로 div에 무언가를 추가함.

toString() : 결과를 문자열로 반환.

 

## .html()

HTML 문서에서 어떤 요소의 내부 내용을 알아내고자 할때 사용.

만일 선택자에 의해 선택된 요소가 복수개일 경우 제일 처음 요소의 값만 취함.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin:8px; font-size:20px; color:blue;
      cursor:pointer; }
  b { text-decoration:underline; }
  button { cursor:pointer; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <p>

    <b>Click</b> to change the <span id="tag">html</span>
  </p>
  <p>

    to a <span id="text">text</span> node.
  </p>
  <p>
    This <button name="nada">button</button> does nothing.
  </p>
<script>
    $("p").click(function () {
      var htmlStr = $(this).html();
      $(this).text(htmlStr);
    });

 

    $("div").html("<span class='red'>Hello <b>Again</b></span>"); // div 요소안에 내용 추가.

 

    $("div").html("<b>Wow!</b> Such excitement...");
    $("div b").append(document.createTextNode("!!!"))
              .css("color", "red"); // html()함수로 html을 추가한 뒤, append() 함수를 사용해 느낌표를 더 추가.


</script>

</body>
</html>

 

## .val()
양식(form)에 들어있는 value 들을 제어할 수 있는 함수.

$('select.foo option:selected').val();    // 드롭박스에서 선택된 것을 가져옴
$('select.foo').val();                    // 드롭박스에서 좀더 쉽게 값을 가져옴
$('input:checkbox:checked').val();        // 체크가 된 체크박스의 값을 가져옴
$('input:radio[name=bar]:checked').val(); // 라디오버튼 중 선택된 값을 가져옴

 

*드롭박스에서 선택된 것들을 표시해 줍니다. 하나만 선택가능하면 string이 반환되고 여러개가 선택가능하면 선택된 값을 배열로 반환 받습니다.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; margin:4px; }
  b { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <p></p>
  <select id="single">
    <option>Single</option>
    <option>Single2</option>

  </select>
  <select id="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>

    <option selected="selected">Multiple3</option>
  </select>
<script>
    function displayVals() {
      var singleValues = $("#single").val();
      var multipleValues = $("#multiple").val() || [];
      $("p").html("<b>Single:</b> " +
                  singleValues +
                  " <b>Multiple:</b> " +
                  multipleValues.join(", "));
    }

    $("select").change(displayVals);
    displayVals();

</script>

</body>
</html>

 

 

반응형

'# Work > └ jQuery' 카테고리의 다른 글

jquery selector의 종류 (스크랩. 내용 중복 유)  (0) 2014.01.21
each()  (0) 2014.01.09
show & hide  (0) 2012.04.26
jquery 내용 정리  (0) 2012.04.18
첫번째 자식 선택하여 스타일 주기.  (0) 2012.04.18
호정찐