Dragonball Online Goku Hand
본문 바로가기
jQuery

속성 관련 메서드

by 별의 코비 2022. 9. 4.
728x90

🧷 jQuery : 속성 관련 메서드

➰ attr() 메서드

선택한 요소의 attribute(속성)를 선택, 생성, 변경할 수 있습니다.

실행 분류 형식
취득 $("a").attr("href");
생성, 변경 $("a").attr("href", "http://www.icoxpublish.com/").attr("target", "_blank");
$("a").attr({href: "http://www.icoxpublish.com/", target: "_blank"});
콜백 함수 $("a").attr("href", function(index, h) {
 // index는 각 a 요소의 index 0,1,2
 // h은 각 a 요소 href 속성
return attribute (속성) // 각 a 요소의 속성을 생성 및 변경합니다.
});
....
<a href="http://www.daum.net" target="_blank" title="새창">다음</a>
<a href="http://www.naver.com" target="_blank" title="새창">네이버</a>
<a href="http://www.nate.com" target="_blank" title="새창">네이트</a>

➿ attr() 메서드 사용 예시

<!DOCTYPE html> 
<html lang="ko">  
<head> 
    <meta charset="UTF-8">  
    <title>attr() 메서드</title> 
    <script src="jquery-3.3.1.min.js"> </script>  
    <script>  
        $(document).ready(function() {
            console.log($("#site >  a:eq(0)").attr("href"));
            $("#site >  a:eq(1)").attr("href", "http://m.naver.com").text("네이버 모바일");
            $("#site a").attr("title", function() {
                return "새창";
            });
        });
    </script> 
</head>  
<body> 
    <div id="site"> 
        <a href="http://www.daum.net" target="_blank">다음</a> 
        <a href="http://www.naver.com" target="_blank">네이버</a> 
        <a href="http://www.nate.com" target="_blank">네이트</a> 
    </div> 
</body> 
</html> 

⭐️ 결과 ⭐️


➰ prop() 메서드

attr()가 html attribute(속성)에 관련된 메서드라면 prop()은 자바스크립트 property(프로퍼티)에 관련된 메서드입니다.
prop() 메서드는 요소의 속성을 true/, false로 제어할 수 있습니다.

➿ prop() 메서드 사용 예시

<!DOCTYPE html> 
<html lang="ko"> 
<head> 
    <meta charset="UTF-8"> 
    <title>prop() 메서드</title> 
    <script src="jquery-3.3.1.min.js"></script> 
    <script> 
        $(document).ready(function() {
            console.log($("input:checkbox").eq(0).attr("checked"));
            console.log($("input:checkbox").eq(1).prop("checked"));
            $("input:checkbox").eq(0).attr("checked", "checked");
            $("input:checkbox").eq(1).prop("checked", true);
            console.log($("input:checkbox").eq(0).attr("checked"));
            console.log($("input:checkbox").eq(1).prop("checked"));
        });
    </script> 
</head> 
<body> 
    <input type="checkbox" id="html"><label for="html">html</label>
    <input type="checkbox" id="css"><label for="css">css</label>
</body> 
</html>

⭐️ 결과 ⭐️

attr() 메서드는 checked 속성이 요소에 추가되는 반면 prop() 메서드의 true는 자바스크립트의 프로퍼티로 처리됩니다.

'jQuery' 카테고리의 다른 글

스타일 관련 메서드  (3) 2022.09.04
클래스 관련 메서드  (3) 2022.09.04
jQuery : 탐색 선택자  (12) 2022.08.31
jQuery : 필터 선택자  (10) 2022.08.31
jQuery : 속성 선택자  (16) 2022.08.30

댓글