JS 잡기술들
[ e.stopPropagation(); ]
=> 자식 태그에 이벤트 시도 시, 자기것만 터트리고
부모태그로 올라가며 찾는 propagation 을 stop 시키는 것
[ 버블링의 활용 / 이벤트 위임 ]
- 반대로, stopPropagation() 하지않고,
자식 이벤트 발생 시 => 부모 이벤트를 연계해서 발생시키는 식으로 유용하게 활용
- 버블링 사용시 주의
=> 부모한테 걸어두고, 부모 이벤트를 발생시키면 => 자식들 모두에게 이벤트가 발생해버림
=> 이벤트 발생 타겟을 제한해야 함
if (!e.target.matches('#fruits > li')) {
return;
}
=> 이벤트가 발생한 target이 부모의 자식 태그가 아니라면 => return 시켜서 막기
[ 키보드 이벤트 활용 ]
$input.addEventListener('keyup', function(e) {
console.log(e);
if (e.key === 'Enter') {
$msg.textContent = $input.value;
$input.value = '';
}
});
[ addEventListener ]
$btn.addEventListener('click', hello);
$btn.addEventListener('click', function() {
});
[ removeEventListener ]
$btn.removeEventListener('click', hello);
[ 배열 / 객체 / 함수 ] 일때는 const 사용!
[ 프로퍼티 방식 ]
key -value 세트 : 프로퍼티
{
name : 'zzz',
age : 30,
onclick: ƒ sayHello()
}
프로퍼티에 이벤트를 거는 방식
=> 브라우저에 '이벤트 위임'
( 브라우저 너가 호출해라 )
내가 부르는게 아니라, 브라우저가 호출해야 되는거니까
sayHello() 함수호출로 하면 안되고
sayHello 함수 자체를 정의해둬야 한다.
$b1.onclick = sayHello;
혹은 익명함수로
$b1.onclick = function(){};
[ 이벤트핸들러 제거 null ]
$b3.onmouseenter = null;
[ JavaScript => Form 태그 동적 생성 ]
// 동적 태그에 이벤트로 form 태그 생성
$("#oneboardRes" + oneboardId).on("click", "button", function(){
//create element (form)
var newForm = $('<form></form>');
//set attribute (form)
newForm.attr("method","post");
newForm.attr("action","/egovproject/" + oneboardId + "/updateboard.do");
// create element & set attribute (input)
newForm.append($('<input/>', {type: 'text', name: 'title', value:boardTitle }));
newForm.append($('<input/>', {type: 'text', name: 'contents', value:boardContents }));
newForm.append($('<input/>', {type: 'submit', value:'등록' }));
// append form (to body)
newForm.appendTo("#oneboardEdit" + oneboardId);
// submit form
//newForm.submit();
});
[ cursor : pointer ]
style='cursor:pointer'
[ return false; ]
:동작 종료
if(sessionId==""){
alert("로그인이 필요합니다.");
return false; }
[ style = "display : none" ]
< ~ style="display:none" >
- 처음에 안보이게 해놓고 => 나중에 속성으로 보여주기 ( AJAX )
$("~").css("display", "inline");
[ play( ) 바로 재생 ]
document.getElementById("mp3").play();
[ placeholder ]
<% if(session.getAttribute("id") != null) { %>
<% } else { %>
<textarea placeholder = "로그인 후 작성해주세요." width="300px" readonly></textarea>
- 세션 있을 경우 / 없을 경우 => 다르게 placeholder 주기
- 세션 없을 경우 readonly 줘서 작성 안되게 해두기
[ <span class=" "> 내용 </span> ]
-한 줄의 text를 중간에 구분해서 속성주기
<span class="user"> <span class="id"> ${sessionScope.id} </span> 님 환영합니다! </span>
[ 삼항 연산자 : 사용 / 세션아이디 적용 ]
- 비밀글 세션아이디랑 작성자 일치하면 보여주고 : 비밀글아니면 보여주고 : 비밀글이면 안보여줌
+ (item.secret == 1 && sessionId == item.writer ? "<p class='contents'>" + item.contents + "</p>"
: (item.secret != 1 ? "<p class='contents'>" + item.contents + "</p>"
: " "))
- 세션아이디가 일치하면 input 태그를 생성 / 아니면 아예 수정/삭제 버튼이 안나오게 끔
+ (sessionId == item.writer ? "<input class='updateBtn' type='button' value='수정'><input class='deleteBtn' type='button' value='삭제'>"
: " " )
[ JS each 반복문 ]
$.each( list, function( i, item ) { }
list : 뽑을 대상
i : 반복문 index ( 0 부터 끝까지 자동 ++ )
item : 하나씩 담는 변수
- 혹은 JSTL <c:forEach > 사용
[ 태그 안에 값 넣기 ]
- li td 등, append 로 태그를 생성하게 만들어두었을 때,
$("#comment").append("<li></li>");
$("#comment li : last-child").addClass( "commentList" + i );
: comment 태그의 (띄어쓰기) 자식인 li 태그 중에서 : last-child 마지막인 li 에다가 class 를 줘놓고 사용
- 반복문으로 그 해당.class == 즉 마지막 list 태그에 append 해서 안에 내용을 넣음
$(".commentList" + i ).append( );
[ $(function(){ $.ajax({}); } ]
- 페이지 뜨자마자 바로 ajax 시작
[ * JSP 경로 필살기 ]
<c:set var="path" value="${ pageContext.request.contextPath }"/>
- 경로 앞에 붙여주기 ( static /~ 부터 시작 )
<link rel="stylesheet" href="${path}/css/oneboard.css">
<script src="${path}/js/jquery-3.6.0.min.js"></script>
( - <!DOCTYPE html> 위에 지시자 태그 쪽에서 같이 선언해서 사용 )
[ jsp include 경로 - webapp~ 부터시작 ]
<jsp:include page = " /WEB-INF/views/header.jsp" />
[ confirm 주기 ]
$("#editbtn").on("click", function (e){
if( !confirm("게시글을 수정하시겠습니까?") ){
e.preventDefault( );
} else {alert("수정이 완료되었습니다.")}
[ 세션 필요없는 페이지에서 세션생성 안하기 ]
<%@ page session="false" %>
[ responseEntity 응답형식 ] ( JSON.stringify(res)해서 확인 )
: .headers/.body/.statusCode/.statusCodeValue
console.log(res.responseEntity.statusCode);
console.log(res.responseEntity.statusCodeValue);