웹 개발

[jquery] attr과 prop 차이 (attr vs prop)

노루아부지 2019. 7. 24. 00:04

1. 개요

jQuery 1.6/1.6.1에서 .attr()와 .prop()로 나눔 ( checkbox에 버그가 존재해서 )

 

* 공식 API 문서 ( http://api.jquery.com/prop/ )

  The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

 

2. .attr(), .prop()의 차이

  • .attr() : HTML의 속성(attribute)을 취급
  • .prop() : javascript의 프로퍼티(property)를 취급 ( 프로퍼티는 javascript에서 사용하는 정보. 상태값. )
    • checked, selected, disabled


- 위의 표에서 알 수 있듯, attr은 초기값을 가져오기 때문에 화면에서 체크박스를 체크/체크해제 한 후 다시 함수를 호출해도 같은 값을 return한다.

 

3. 결론

  • .attr()을 사용할 경우 아래와 같은 오류가 발생할 수 있다.
  • .attr(“checked”)를 사용할 경우 “초기값”을 가져오기 때문에 현재 상태를 가져오기 위해서 사용했을 경우 오동작이 발생한다.
  • .attr(“checked”, “checked”) 또는 .attr(“checked”, true) 와 같이 값을 setting하기 위해서 사용할 경우 값이 setting되지 않거나, 
  • setting 되더라도 화면의 모든 action이 정지되어버리는 상황이 발생할 수 있다.
  • selected, checked, disabled 와 같은 속성은 .prop()로 제어해야 한다.

 

[참고]

http://stackoverflow.com/questions/5874652/prop-vs-attr 

http://api.jquery.com/prop/

http://javascriptandjquerydev.blogspot.kr/2012/07/attr-prop.html

 

728x90

'웹 개발' 카테고리의 다른 글

연산자 우선순위  (0) 2019.07.24
++i 와 i = i + 1 의 비교  (0) 2019.07.24
jquery live method 삭제(remove)  (0) 2019.07.23
[IE] internet explorer autocomplete off  (0) 2019.07.23
JAVA에서 cmd 실행해서 wkhtmltopdf 실행방법  (0) 2019.07.21
loading