예시
이번 주에는 1주차에 만들었던 쇼핑몰에 환율 정보를 추가해줄 것이다.
로딩이 완료되면, 환율 API를 이용해서 환율을 표시해주면 된다.
🙋♀️ 로딩 완료 후에 환율을 나타내려면 어떻게 해야할까?
페이지 로드 후 실행하기 (window.onload, document.ready) / document.ready를 순수자바스크립트로! (DOMContentLo
스크립트를 위쪽에서 불러오면 요소를 찾지 못하는 오류를, 아래쪽에서 불러오면 느린 로딩속도 등의 이유로 우리는 스크립트 내에서 페이지로드 후 불러오는 함수를 사용하곤 한다. 대표적으
mesonia.tistory.com
우리는 jQuery를 사용하고 있으므로 document.ready
를 이용해서 로딩 완료후에 실행되도록 할 수 있다.
$(document).ready(function(){
alert('다 로딩됐다!')
});
🤔 내가 작성한 코드
더보기
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR&display=swap" rel="stylesheet">
<title>나만의 쇼핑몰 페이지</title>
<style>
* {
font-family: 'Noto Serif KR', serif;
}
.page-container {
width: 900px;
margin: auto;
padding: 20px;
box-sizing: border-box;
}
.prize-picture {
width: 600px;
height: 400px;
text-align: center;
margin: auto;
background-image: url('https://shop-phinf.pstatic.net/20210331_110/1617152101014eIg2y_JPEG/18287996619697229_917030031.jpg?type=m510');
background-size: cover;
background-position: center;
border-radius: 4px;
}
.detail {
width: 700px;
margin: auto;
margin-top: 20px;
}
.prize-title {
margin: 30px 0;
}
.pink {
background: #ff9193;
color: white;
}
.price {
font-size: 15px;
margin-left: 15px;
}
.title {
margin-bottom: 25px;
}
.btn-primary {
width: fit-content;
display: block;
margin: auto;
}
.rate {
color: blue;
}
</style>
<script>
function order() {
alert('주문이 완료되었습니다!👏')
}
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rate",
data: {},
success: function (response) {
let rate = response['rate']
$('#rate').text(`달러-원 환율: ${rate}`)
}
})
})
</script>
</head>
<body>
<div class="page-container">
<div class="prize-picture">
</div>
<div class="detail">
<div class="prize-title">
<h2 class="title">에스쁘아 립스틱 노웨어 젠틀 매트 <span class="price">가격: 6,900원 / 개</span></h2>
<p>에스쁘아 립스틱 노웨어 젠틀매트 <span class="pink">#핑크 밋츠 캐러멜 !</span> <br/>
컬러 네이밍처럼 핑크에 캐러멜의 달콤함과 부드러움을 표현한 컬러! <br/>
러블리함과 동시, 분위기 뿜뿜한 메이크업 룩을 연출할수 있답니다~!
</p>
<p id="rate" class="rate"></p>
</div>
<h2 class="title">주문하기</h2>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default-name">주문자 이름</span>
</div>
<input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">수량</label>
</div>
<select class="custom-select" id="inputGroupSelect01">
<option selected>-- 수량을 선택하세요 --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default-address">주소</span>
</div>
<input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">전화번호</span>
</div>
<input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
</div>
<button type="button" class="btn btn-primary" onclick="order()">주문하기</button>
</div>
</body>
</html>
🎁 결과
페이지가 로드되면 함수를 호출하는 방식을 알 수 있었다!
그리고 텍스트를 변경하는 방법이 가물가물해서 2주차 내용들을 다시 보면서 잘 적용할 수 있었다!
나는 비어있는 p 태그에 id만 추가한 뒤 리터럴 방식으로 `달러-원 환율: ${rate}`
이렇게 바로 작성되도록 했고,
<p id="rate" class="rate"></p>
$('#rate').text(`달러-원 환율: ${rate}`)
강의 코드에서는 "달러-원 환율: "이 작성된 p 태그 내부에 가져올 환율을 작성할 span 태그를 따로 작성해서 id를 가져와서 텍스트를 수정하는 방식으로 작성되었다.
<p class="rate">달러-원 환율: <span id="now-rate">1219.15</span></p>
이 방식이 코드를 읽을 때 좀 더 이 부분에 무엇이 추가되어있는지 직관적으로 알기 쉬운 것 같다.