1. 2015.04.27 jQuery .attr() vs .prop()

jQuery .attr() vs .prop()

jQuery에서 .attr()과 .prop()은 사용시 몇가지 차이점이 있다.


.attr()의 경우 이름 그대로 attribute를 컨트롤 하기위함이고, .prop()의 경우 property를 컨트롤할때 사용한다.


간단한 예를 들어서..


<input type="checkbox" id="check" checked="checked" />
<label for="check">Check Me...</label>
$('#check').change(function() {
    var $input = $(this);
    console.log(".attr('checked'): " + $input.attr('checked'));
    console.log(".prop('checked'): " + $input.prop('checked'));
    console.log(".is('checked'): " + $input.is('checked'));
}).change();


위 체크박스를 클릭시..


.attr()의 경우 체크여부와 상관없이 항상 'checked'만을 리턴하고..

.prop()의 경우 체크여부에 따라 true, false를 리턴한다.


단, jquery 1.6 이전 버전엔 .prop()이 없으니 버전을 확인하고 사용해야한다.

'WebDevelop > jQuery' 카테고리의 다른 글

영역내에서 마우스 휠되도록...  (0) 2016.06.28
jQuery와 prototype의 충돌 해결방법  (0) 2013.05.13
jQuery selector시 좋은 습관  (0) 2009.10.13
Return top