사소한 개발지식/JavaScript

Jquery attr()를 이용한 속성값 제어

KimBY 2019. 5. 31. 16:53
728x90
반응형

동적인 웹페이지를 위해 HTML 태그의 속성값을 가져오거나 변경해야하는 경우가 많다

 

이럴 때 사용하기 좋은 Jquery 매서드가 attr() 매서드이다.

 

 

■ 속성값 가져오기

 

  - attr(attributeName)

<!DOCTYPE html>
<html lang="ko">
<head>
	<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
	<style>
		.test {cursor:pointer;}
	</style>
</head>
<body>
	<div class='test' msg='hi'>안녕하세요<div>
	<script>
		$('.test').click(function () {
			alert($(this).attr('msg')); // 
 		});
	</script>
</body>
</html>

attr() 예시

test 클래스를 포함한 태그의 msg값을 alert하기 때문에 hi라는 alert가 발생한다.

 

 

속성값 변경하기

 

 - attr(attributeName, '변경값')

<!DOCTYPE html>
<html lang="ko">
<head>
	<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
	<img id='test_img' src="이미지1" style="width:50px;height:50px;"/>
	<div class='test' style="cursor:pointer;">변경<div>
	<script>
		$('.test').click(function () {
			$('#test_img').attr('src', '이미지2');
 		});
	</script>
</body>
</html>

attr() 예시2

test_img라는 id값을 가진 태그의 src속성값을 변경하여 img가 변경된다.

728x90
반응형