[상황]
orderList.jsp 내 아래의 java script 파일들을 불러와서 실행,
1) orderList.js
2) orderList_goDetail.js
orderList.js만 실행되고
orderList_goDetail.js는 실행되지 않음
[파일 분석]
1. orderList.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<!--java script 파일 불러오기-->
<script src="/js/orderList_goDetail.js"></script>
<script src="/js/orderList.js"></script>
</head>
<body>
<div id="orderlist_content-btns">
<div>
<input class="goDetail" type="button" value="주문 상세" data-odno="${order.odNo}">
</div>
</div>
</body>
java script 두 개를 head 부분에 불러왔다.
2. orderList.js
window.onload = function () {
// q&a 바로가기 연결
const goQna = document.getElementById("goQna");
const goFaq = document.getElementById("goFaq");
// 계좌번호 복사하기 버튼 불러오기 후 변수에 담기
const copyBtn = document.getElementById("copyBtn");
// 메일 보내기 변수
const copyMail = document.getElementById("copyMail");
const slrMail = document.getElementById("slrMail_copy").textContent;
// Q&A 게시판 이동
if (goQna) {
goQna.addEventListener("click", function() {
console.log('Button clicked!');
ToGoQna();
});
} else {
console.error('Element with id "goQna" not found!');
}
... 생략 ...
}
window.onload로 메서드 실행
3. orderList_goDetail.js
window.onload = function () {
const orderButtons = document.querySelectorAll('.goDetail');
orderButtons.forEach(function(button) {
button.addEventListener('click', function() {
console.log('orderButtons clicked!'); // 버튼 클릭 이벤트가 발생하는지 확인
const odNo = this.getAttribute('data-odno');
window.location.href = "/order/orderDetail?odNo=" + odNo;
});
});
}
window.onload로 메서드 실행
[문제 해결 과정]
1. JSP 페이지 내 <script> 태그 위치 변경
1) 원래 스크립트 태그가 <head> 영역에 위치
2) window.onload 이전에 다른 스크립트에서 오류 발생할 경우
위 두 개의 경우로 인하여 window.onload가 호출되지 않을 때가 있다.
<script> 태그를 <body> 영역 맨 아래에 위치시키면 해결 가능할 수도 있음
-> 위치 변경해봤지만 어림도 없었다.
2. window.addEventListener('load', function() {}) 사용
window.onload는 한 페이지에서 한 번만 사용 가능하다.
만약 다른 java script 파일에서 window.onload를 다시 정의한다면,
첫 번째 파일의 window.onload는 실행되지 않는다.
이런 경우, 다른 파일을 window.addEventListener('load', function() {}) 사용
-> orderList.js 파일은 window.onload, orderList_goDetail.js 파일은 위의 방법 사용했더니 해결되었다.
[문제 해결 완료]
orderList_goDetail.js 파일 내용 변경
window.addEventListener('load', function () {
const orderButtons = document.querySelectorAll('.goDetail');
orderButtons.forEach(function(button) {
button.addEventListener('click', function() {
console.log('orderButtons clicked!'); // 버튼 클릭 이벤트가 발생하는지 확인
const odNo = this.getAttribute('data-odno');
window.location.href = "/order/orderDetail?odNo=" + odNo;
});
});
});
잘 실행됨 !
'[Language] > VIEW' 카테고리의 다른 글
[JS] Java Script 버전 확인 (0) | 2024.01.06 |
---|---|
[css] 효과 모음 (0) | 2023.12.15 |
[JS/forEach] 메서드 인자를 여러 개 지정하기 (0) | 2023.12.09 |
[CSS] <hr> 색상 변경 (0) | 2022.10.29 |
[CSS] 그림자 효과 (box-shadow) (0) | 2022.10.29 |