WEB/JQuery
[JQuery] 버튼 누르면 동작 -전구에 불 끄고 키기
애플쩀
2022. 5. 27. 14:25
버튼한개
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<!-- jQuery로 바꾸기 -->
<img src="../images/pic_bulboff.gif" alt="" id="img_bulb" />
<br>
<button id="btn">Turn On</button>
<script>
$("#btn").click(function(){
/* 매치하는 문자열이 없을경우 null 반환
js는 null도 false라고 인식하기때문에
==null, false 두개로 사용 가능하다 */
if(!$("img").attr("src").match("off.gif")){
$("img").prop("src","../images/pic_bulboff.gif");
$("#btn").text("turn on");
}else{
$("img").prop("src","../images/pic_bulbon.gif");
$("#btn").text("turn off");
}
});
</script>
</body>
</html>
버튼 두개
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h3>ex01_03 html 요소 속성변경</h3>
<button>trun on</button>
<button disabled="disabled">turn off</button>
<img src="../images/pic_bulboff.gif" alt="" id="imgbulb">
<script>
$("button:first-of-type").click(function(event){
$("#imgbulb").attr("src","../images/pic_bulbon.gif");
/* $(this).prop("disabled", true);
$(this).next().prop("disabled", false); */
$(this).prop("disabled", true)
.next().prop("disabled", false);
});
$("button:last-of-type").click(function(event){
$("#imgbulb").attr("src","../images/pic_bulboff.gif");
$(this)
.prop("disabled", true)
.prev().prop("disabled", false);
});
</script>
</body>
</html>