반응형

** jquerykorea.net 사이트를 보면서 개인적으로 보기 쉽게 정리한 내용.

 

## jQuery(':gt(index)') 

요소 집합에서 index 보다 큰 색인을 가지고 있는 요소들을 반환.

즉, gt(0) 이면 0보다 큰 인덱스를 가진 녀석들 모두를 선택할 수 있습니다.

<script>$("td:gt(4)").css("text-decoration", "line-through");</script>

 

## jQuery(':lt(index)')

요소 집합에서 index 보다 작은 색인을 가지고 있는 요소들을 반환.

즉, gt(3) 이면 3보다 작은 인덱스를 가진 녀석들 모두를 선택할 수 있습니다.

<script>$("td:lt(4)").css("color", "red");</script>

 

## jQuery(':empty')

해당 요소의 텍스트가 없을 때 선택되어짐.

텍스트도 자식요소라 생각한다.

<script>$("td:empty").text("Was empty!").css('background', 'rgb(255,220,200)');</script>

 

 ## jQuery('[attribute]')

attribute 에 해당하는 속성이 있는 확인하는 선택자

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
  <div>no id</div>
  <div id="hey">with id</div>

  <div id="there">has an id</div>
  <div>nope</div>
<script>

    $('div[id]').one('click', function(){
      var idString = $(this).text() + ' = ' + $(this).attr('id');
      $(this).text(idString);
    });
</script>

</body>
</html>

 - one() 이라는 함수는 해당 객체에 이벤트를 묶어주는 함수

div 에 id 값이 있다면 onclick 이라는 이벤트를 묶어(bind)주라는 뜻

 

## jQuery(':has(selector)')

자식 요소들 중에 특정 요소를 찾을 수 있다

<script>$("div:has(p)").addClass("test");</script>

- div 중에 paragraph(p 태그)를 가지고 있으면 "test" 라는 클래스를 적용한다.

 

## jQuery(':header')

h1, h2, h3 와 같은 제목 요소(header element)들을 선택해 줌

<script>$(":header").css({ background:'#CCC', color:'blue' });</script>

## jQuery(':hidden')

화면에 보이지 않는 요소들을 찾아 줌

<!DOCTYPE html>
<html>
<head>
  <style>
  div { width:70px; height:40px; background:#ee77ff; margin:5px; float:left; }
  span { display:block; clear:left; color:red; }
  .starthidden { display:none; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <span></span>
  <div></div>
  <div style="display:none;">Hider!</div>
  <div></div>

  <div class="starthidden">Hider!</div>
  <div></div>
  <form>
    <input type="hidden" />

    <input type="hidden" />
    <input type="hidden" />
  </form>
  <span>

  </span>
<script>
    // in some browsers :hidden includes head, title, script, etc... so limit to body
    $("span:first").text("Found " + $(":hidden", document.body).length +
                         " hidden elements total.");
    $("div:hidden").show(3000);
    $("span:last").text("Found " + $("input:hidden").length + " hidden inputs.");
</script>

</body>
</html>

 

- 보이지 않는 div 를 3초 후에 보이게 하고 hidden input 들을 모두 찾아서 개수(숫자를 세다)합니다.

 

 

## jQuery('#id')

요소의 id 속성값을 이용해서 원하는 요소를 찾을 수 있습니다.

<script>$("#myDiv").css("border","3px solid red");</script>

 

"myID.entry[1]" 이라는 특수문자가 섞인 id . 특수문자가 섞여있을 때는 백슬래시를 사용함.

<script>$("#myID\\.entry\\[1\\]").css("border","3px solid red");</script>

 

 ## jQuery('[attributeFilter1][attributeFilter2][attributeFilterN]')

attributeMultiple selector (다중 속성필터)

- 동일한 형태의 요소들이 많을 경우 그 범위를 줄이기 위해 이 방법을 사용.

[name="value"][name2="value2"] 와 같이 대괄호([])안에 조건을 넣고 필요한 만큼 반복하면 됨.

 

- id 속성이 있는 input 태그를 찾은 뒤에 name 속성의 값에 "man"이라는 텍스트가 뒤쪽에 있는지 확인하여 "only this one" 이라는 문자를 value 에 세팅.

<script>$('input[id][name$="man"]').val('only this one');</script>

 

## jQuery('prev + next')

현재 선택된 요소를 기준으로 그 다음 선택자와 일치하는 첫번째 요소를 찾아 줌.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <form>

    <label>Name:</label>
    <input name="name" />
    <fieldset>
      <label>Newsletter:</label>

      <input name="newsletter" />
    </fieldset>
  </form>
  <input name="none" />
<script>$("label + input").css("color", "blue").val("Labeled!")</script>

</body>
</html>

- label 요소 바로 다음에 오는 input 요소를 찾아서 "Labeled!' 라는 문자를 넣음.

 

* (prev + next) 와 (prev ~ sibilings)의 차이점.

prev + next 는 prev 에 해당하는 선택자를 기준으로 next 에 해당하는 요소를 깊이에 상관없이 선택을 할 수 있습니다.

반면 prev + sibilings 는 prev 에 해당하는 같은 깊이의 다음 요소를 선택할 수 있다는 겁니다.

즉, 전자는 형제 요소와 무관하고 후자는 같은 부모 요소를 둔 형제요소를 선택할 수 있다는 뜻입니다.

 

## jQuery(':not(selector)')

부정형 선택자.

<script>
  $("input:not(:checked) + span").css("background-color", "yellow");
  $("input").attr("disabled", "disabled");
</script>

- 체크가 되어 있지 않은 체크박스를 찾고 그 바로 다음 요소를 찾아서 바탕색을 노란색으로 바꿈.

 

 ## jQuery(':nth-child(index/even/odd/equation)')

자식 요소 집합에서 선택한 색인에 위치한 자식을 찾는 요소.

index 1이 초기값이며 색인에 맞는 자식 요소를 찾는다. even, odd, equation 이라는 문자열도 사용할 수 있음.

(예. :nth-child(event), :nth-child(4n))

<script>$("ul li:nth-child(2)").append("<span> - 2nd!</span>");</script>

 

  * :odd ; 홀수번째 요소 찾기

<script>$("tr:odd").css("background-color", "#bbbbff");</script>

 

## jQuery(':only-child')

자기가 유일한 자식인 요소를 찾아줌. (형제가 없는)

 

  * 형제가 없는 버튼을 찾아서 색을 바꿔줌.

<!DOCTYPE html>
<html>
<head>
  <style>

  div { width:100px; height:80px; margin:5px; float:left; background:#b9e }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <div>
    <button>Sibling!</button>
    <button>Sibling!</button>
  </div>

  <div>
    <button>Sibling!</button>
  </div>
  <div>
    None
  </div>

  <div> 
    <button>Sibling!</button>
    <button>Sibling!</button>
    <button>Sibling!</button>

  </div>
  <div>
    <button>Sibling!</button>
  </div>
<script>$("div button:only-child").text("Alone").css("border", "2px blue solid");</script>

</body>
</html>

 

## jQuery(':parent')

텍스트 노드를 포함한 요소를 가지고 있는 상위 요소를 찾음.

이 선택자는 :empty 선택자와 반대 선택자. (:child 가 아닌것에 주목.)

 

  * 텍스트를 포함한 자식요소가 있는 td를 찾아서 바탕색을 서서히 연하게(알파값) 변화시킴.

<!DOCTYPE html>
<html>
<head>
  <style>
  td { width:40px; background:green; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <table border="1">

  <tr><td>Value 1</td><td></td></tr>
  <tr><td>Value 2</td><td></td></tr>

</table>
<script>$("td:parent").fadeTo(1500, 0.3);</script>

</body>
</html>

// faceTo(a, b) - a 시간동안 b만큼 알파값을 변화시켜라.

 

 

## jQuery(':password')

input 의 type이 password 인 요소를 찾음.

 

## jQuery(':radio')

input 의 type이 radio인 요소를 찾음.

<srcipt>$("form input:radio").wrap('<span></span>').parent().css({background:"yellow", border:"3px red solid"});</script>

 

## jQuery(':reset)

input 의 type이 reset인 요소를 찾음.

 

## jQuery(':selected')

:selected 선택자는 <option> 태그 전용. 체크박스나 라디오 버튼은 :checked 선택자를 사용해야 함.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <select name="garden" multiple="multiple">

    <option>Flowers</option>
    <option selected="selected">Shrubs</option>
    <option>Trees</option>
    <option selected="selected">Bushes</option>

    <option>Grass</option>
    <option>Dirt</option>
  </select>
  <div></div>
<script>

    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .trigger('change');
</script>

</body>
</html

// change 함수 -  뭔가가 변화된다면 호출되는 함수.

기본 자바스크립트의 onchange와 같은 역할.

each 함수 - 선택된 것이 있는 만큼 루프(Loop)를 돌리는 함수.

 

## jQuery(':submit')

input 의 type이 submit 버튼인 요소를 찾음.

<!DOCTYPE html>
<html>
<head>
  <style>
  textarea { height:45px; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
 
<table>
<form>
<table id="exampleTable" border="1" cellpadding="10" align="center">

    <tr>
        <th>
            Element Type
        </th>
        <th>
            Element
        </th>

    </tr
    <tr>
        <td>
            <input type="button" value="Input Button"/>
        </td>

    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="file" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="hidden" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="image" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="password" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="radio" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="reset" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="submit" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="text" />
        </td>

    </tr>
    <tr>
        <td>
            <select><option>Option</option></select>
        </td>

    </tr>
    <tr>
        <td>
            <textarea></textarea>
        </td>
    </tr>

    <tr>
        <td>
            <button>Button</button>
        </td>
    </tr>
    <tr>
        <td>
            <button type="submit">Button type="submit"</button>
        </td>
    </tr>

</table>
</form>
<div id="result"></div>

<script>
    var submitEl = $("td :submit")
      .parent('td')
      .css({background:"yellow", border:"3px red solid"})
    .end();
   
    $('#result').text('jQuery matched ' + submitEl.length + ' elements.');

    // so it won't submit
    $("form").submit(function () { return false; });
    
    // Extra JS to make the HTML easier to edit (None of this is relevant to the ':submit' selector
    $('#exampleTable').find('td').each(function(i, el) {
        var inputEl = $(el).children(),
            inputType = inputEl.attr('type') ? ' type="' + inputEl.attr('type') + '"' : '';
        $(el).before('<td>' + inputEl[0].nodeName + inputType + '</td>');
    })
   

</script>

</body>
</html>

 

 

//  td :submit - td안에 submit 버튼이 있으면 .

 

- 일단 exampleTable을 찾아서 td 요소 수만큼 Loop 를 돌리는 each()함수를 실행 시키고 있습니다. 그 안에서는 el 이란 변수가 있는데요. 이 el이 td 가 되겠습니다. td의 children() 즉, 자식 요소를 찾아서 3항식을 이용해 문자열을 만듭니다. 만약 그 요소에 type이라는 속성이 있으면 문자열을 만들어 내고 있죠. 그리고 el 즉 현재의 td 앞쪽에 (before 함수를 사용했습니다.) 새로운 td를 추가해놓고 있습니다.

 

## jQuery(':text')

input 의 type이 text버튼인 요소를 찾음.

$(':text') 선택자는 $('[type=text]') 로 대체하여 사용할 수 있다.

 

## jQuery(':visible')

:visible 선택자는 눈에 보이는 요소를 찾아 줍니다.

 

* div 중에 보이는 요소라면 클릭시에 노란색으로 변경한다. 버튼을 클릭하면 보이지 않는 요소를 보이게 한다.

<!DOCTYPE html> <html> <head> <style> div { width:50px; height:40px; margin:5px; border:3px outset green; float:left; } .starthidden { display:none; } </style> <script src="http://code.jquery.com/jquery-1.5.js"></script> </head> <body> <button>Show hidden to see they don't change</button> <div></div> <div class="starthidden"></div> <div></div> <div></div> <div style="display:none;"></div> <script> $("div:visible").click(function () { $(this).css("background", "yellow"); }); $("button").click(function () { $("div:hidden").show("fast"); }); </script> </body> </html>

 

 

반응형
호정찐