본문 바로가기

Frontend/jQuery

JS jQuery (part. 23) - 매개변수 context

jQuery 메서드는 매개변수를 두 개 입력할 수도 있다

 

$(selector, context)

 

context는 selector가 적용하는 범위를 한정한다 (일반적으로 이벤트와 함께 사용)

특정 부분에 선택자를 적용하고 싶을 때 사용하는 것이 매개변수 context

 

<style>
  * {
    margin: 0px;
    padding: 0px;
  }

  div {
    max-width: 150px;
    margin: 5px;
    padding: 3px;
    border: 3px solid #000;
    border-radius: 10px;
  }
</style>

<body>
    <div>
        <h1>Header 1</h1>
        <p>Paragraph</p>
    </div>
    <div>
        <h1>Header 2</h1>
        <p>Paragraph</p>
    </div>
    <div>
        <h1>Header 3</h1>
        <p>Paragraph</p>
    </div>
</body>
$(function () {
  $('div').click(function () {
    var header = $('h1', this).text();
    var paragraph = $('p', this).text();

    alert(header + '\n' + paragraph);
  })
});

또는 find( ) 메서드를 사용해도 된다

 

$(function () {
  $('div').click(function () {
    var header = $(this).find('h1').text();
    var paragraph = $(this).find('p').text();

    alert(header + '\n' + paragraph);
  })
});