development/script

jQuery 셀렉터 :button

알 수 없는 사용자 2018. 3. 9. 14:30
반응형

jQuery 셀렉터의 :button은 button 타입의 컨포넌트들을 찾게 됩니다.


예제)

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>button demo</title>
  <style>
  textarea {
    height: 35px;
  }
  div {
    color: red;
  }
  fieldset {
    margin: 0;
    padding: 0;
    border-width: 0;
  }
  .marked {
    background-color: yellow;
    border: 3px red solid;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<form>
  <fieldset>
    <input type="button" value="Input Button">
    <input type="checkbox">
 
    <input type="file">
    <input type="hidden">
    <input type="image">
 
    <input type="password">
    <input type="radio">
    <input type="reset">
 
    <input type="submit">
    <input type="text">
    <select>
      <option>Option</option>
    </select>
 
    <textarea></textarea>
    <button>Button</button>
  </fieldset>
</form>
 
<div></div>
 
<script>
var input = $( ":button" ).addClass( "marked" );
$( "div" ).text( "For this type jQuery found " + input.length + "." );
// Prevent the form from submitting
$( "form" ).submit(function( event ) {
  event.preventDefault();
});
</script>
 
</body>
</html>

실행 모습)



설명)

html 상단에서 style들을 선언하고 중간 부분에서는 각각의 컨포넌트들을 선언한 다음 하단부에서 자바스크립트로 처리를 했습니다.

자바스크립트를 보면...우선 $( ":button" ).addClass( "marked" )는 모든 버튼 형식의 컨포넌트를 찾아 marked라는 클래스를 부여해라는 뜻이지요.

input box의 type이 button이거나 태그 자체가 button 경우가 해당 되므로

첫번째 컨포넌트인 <input type="button" value="Input Button">와 마지막 컨포넌트인 <button>이 해당 됩니다.

그래서 .marked로 지정된 background-color: yellow;border: 3px red solid;이라는 스타일이 2개한테만 적용된 것입니다.


추가적으로 $( "div" ).text( "For this type jQuery found " + input.length + "." ); 이 구문은 div태그의 요소를 찾아 문자열을 넣어줬는데,

input.length 즉 :button 타입을 찾아 input이라는 변수에 담았는데 2개가 찾아졌으니

For this type jQuery found 2. 라는 문자열이 찍히게 된 것입니다.

반응형