제이쿼리 attr() 와 prop() 차이
attr() |
prop() |
.attr(attributeName) |
.prop(propertyName) |
HTML의 속성(attribute)를 다룸 (HTML로 기록되어 있는 속성의 내용) |
Js 객체의 속성(property)를 다룸 (JavaScript가 취급하는 정보) |
return : string |
return :string, boolean, date, function 등 |
Id, class, name 등과 같이 상태가 변해도 변하지 않는 속성을 다룰때 사용 |
상태에 따라 값이 변하는 속성을 다룰 때 사용 Ex) 브라우저에서 checkbox 체크/해제 |
Ex) .attr(‘checked’) -> checked, undefined 실제 html에서 attr을 이용해서 checked입력 |
ex) .prop(‘checked’) -> true/false prop는 html에 checked 옵션을 넣어주지 않음 |
attr보다 2.5배 빠름 |
<body>
<p id="test1">문자열 1</p>
<p id="test2">문자열 2</p>
<input id="test3" type="text" value="홍길동" />
<input id="test3" type="text" value="비밀번호" />
<input id="check1" type="checkbox" value="man" checked>남
<input id="check2" type="checkbox" value="woman">여
<a href="#">네이버</a>
<br>
<input type="button" onclick="check()" value="전송" />
<br>
<input id="txt" type="text" value="abc">
<button>버튼</button>
</body>
<script>
function check(){ //프로퍼티==객체의 속성
//$("#test1")[0].className="ddd"; //객체.prop=값
$("#test1").prop("className","ddd"); //객체.prop=값
//$("#test1").attr("class","ccc"); //html속성,값
console.log($("#check1"));
console.log($("#check1").prop("checked"));
console.log($("#check2").prop("checked"));
//checked, disable, readonly는 prop 권장
console.log($("a").attr("href"));
console.log($("a").prop("href"));
}
$("button").click(function(){
$(this).attr("onclick","alert('ok')");
console.log($("#txt").attr("value"));//html 최초 속성값
console.log($("#txt").prop("value"));//바뀐 값도 가져온다
console.log($("#txt").val()); //바뀐 값도 가져온다
});
-------------------------------------------------------------------------------------------------------
1. $("#test1")[0].className="ddd"; //객체.prop=값
2. $("#test1").prop("className","ddd"); //객체.prop=값
3. $("#test1").attr("class","ccc"); //html속성,값
1번은 제이쿼리 객체의 배열에서 직접적으로 자바스크립트 객체를 선택하여 속성인 className을 변경한다.
2번은 제이쿼리 객체를 제이쿼리 함수를 사용하여 속성인 className을 변경한다.
3번은 제이쿼리 객체를 제이쿼리 함수를 사용하여 html 속성 값인 class를 변경한다.
-----------------------------------------------------------------------------------------------------------
1. console.log($("#txt").attr("value"));//html 최초 속성값
2. console.log($("#txt").prop("value"));//바뀐 값도 가져온다
3. console.log($("#txt").val()); //바뀐 값도 가져온다
최초 입력값인 abc를 1,2,3번 모두 잘 가져온다.
그러나 입력값을 xxx로 바꾸고 버튼을 누르면 1번은 그대로 초기값을 가져오고
2,3번은 변경한 값을 가져온다.
attr()은 정적인 값을 다루는데 쓰고 prop()는 동적인 값을 다루는데 쓴다.