Frontend/JavaScript (32) 썸네일형 리스트형 yarn이란?: yarn 설치하기 Node.js를 설치할떄 패키지를 관리해주는 npm도구가 설치된다. 이때 npm대신 yarn이란 패키지 관리자 도구를 설치하여 사용해도되는데, yarn은 npm을 대체하는 도구로 보다 빠르며 기타 부가 기능을 제공한다. 설치 후 잘 설치되었는지 확인해보자. npm install --global yarn yarn --version 파라미터값에 따른 tab active 유지하기 우선 php로 파라미터 값에 따라 active 클래스가 추가되도록 html에 설정한다. 각 탭이 클릭될때마다 파라미터가 수정/추가되고 reload()되면 끝. //원하는 a 요소 모두 선택 const tabMenuLinks = document.querySelectorAll(".layout_tab ul li > a"); tabMenuLinks.forEach((link) => { link.addEventListener("click", function (event) { event.preventDefault(); // 링크의 기본 동작(페이지 이동) 방지 const linkHref = this.getAttribute("href"); // 클릭한 링크의 href 값을 가져옴 const currentURL = wi.. button 클릭시 페이지가 새로고침될때, preventDefault() button의 기본 동작인 폼 전송(form submission)으로 인해 발생할 수 있다. JavaScript에서 event.preventDefault()를 사용하하면 버튼의 기본동작을 막을 수 있다. event.preventDefault() checkbox value가 submit되지않을때 checkbox는 radio와 다르게 값을 hidden한 input으로 넘겨줘야한다는 사실을 놀랍게도 몇개월에 한번씩 계속 잊고 왜 안되는지 한참을 고민하다 떠올리곤 탄식하는 일이 반복되자.. 반성을 할겸 적어보기로 했다. hidden type input을 추가 onchange시 함수호출 웹 모바일 //checkbox가 선택되었을때 value을 변경한다. function ifCheckedTurnYorN(checkbox, hiddenInputName) { $("input[name='" + hiddenInputName + "']").val(checkbox.checked ? 'Y' : 'N'); } 완료. AJAX, include한 코드에 속성추가하기 아래와 같이 불러온 form에 속성을 추가해보자. $.get('action될 url', function(){ [ $(".contentsFormInclude").html($(data).find("form[name='contentsform']")); }).fail(function(xhr, status, error) { console.error("Error:", error); }); https://standout.tistory.com/797 .attr()로 추가후 원하는방향으로 function을 따로 작성한다, 아래 handleFormSubmit는 예시 $("form[name='contentsform']").attr("onsubmit", "return handleFormSubmit(this);"); funct.. AJAX, 특정영역만 불러오기 .contentsFormInclude안에 특정 파일을 include하되 모든코드말고 특정 영역만 불러와보자. include하는 파일안에 form태그의 name이 contentsform인 영역이 있다고 가정한다면 불러오는 코드 $(".contentsFormInclude").html($(data).find("form[name='contentsform']")); 예시코드 $.get('action될 url', function(){ [ $(".contentsFormInclude").html($(data).find("form[name='contentsform']")); }).fail(function(xhr, status, error) { console.error("Error:", error); }); AJAX, <script> 코드 추가하기 스크립트 추가 $("").text(`cid = 123;`).appendTo(document.head); 변수값으로 추가할경우 $("").text(`cid = ${noValue};`).appendTo(document.head); AJAX, style.css 추가하기 하나씩 추가하는 코드 $("head").append(''); 여러개일 경우 [ '', '' ].forEach(css => $("head").append(css)); 예시코드 $.get('action될 url', function(){ [ '', '' ].forEach(css => $("head").append(css)); }).fail(function(xhr, status, error) { console.error("Error:", error); }); https://standout.tistory.com/794 AJAX, script.js 추가하기 하나씩 추가하는 코드 $.getScript("script.js"); 여러개일 경우 [ '$.getScript("script1.js")', '$.getScript.. AJAX, script.js 추가하기 하나씩 추가하는 코드 $.getScript("script.js"); 여러개일 경우 [ '$.getScript("script1.js")', '$.getScript("script2.js")' ].forEach(script => $.getScript(script)); 예시코드 $.get('action될 url', function(){ [ '$.getScript("script.js")', '$.getScript("script.js")' ].forEach(script => $.getScript(script)); }).fail(function(xhr, status, error) { console.error("Error:", error); }); AJAX 메서드, 비동기적 서버통신 $.get fail $.get('action될 url', function(){ }).fail(function(xhr, status, error) { console.error("Error:", error); }); fail() AJAX 요청이 실패했을때 실행할 콜백 함수 xhr은 XMLHttpRequest 객체를 나타내며, status는 요청 상태 코드를, error는 에러 메시지를 포함한다. Attribute 속성 삭제하기 button의 onclick이라는 속성을 삭제해보자. button.removeAttribute("onclick"); class/id값 없는 button : 어떤버튼이 클릭되었는지, 버튼텍스트인식하기 아래와 같은 수정이란 텍스트를 가진 button을 인식해보기로 하자. 수정 document.querySelectorAll("button").forEach(button => { const buttonText = button.innerText.trim(); if (buttonText === '수정') {} }); alert와 confirm의 차이, 예시코드 alert 통보식 안내창 alert("알림창으로 안내드릴게요!"); confirm 허락을 구하는 안내창 if (confirm("정말로 진행하시겠습니까?")) { console.log("진행합니다!"); } else { console.log("취소했습니다."); } hoisting, 사용할 변수를 미리 확인하다 hoisting JavaScript에서 사용할 변수를 미리 확인해 끌어올려지는 작업 sayHello(); // "Hello!" function sayHello() { console.log("Hello!"); } sayHello()함수를 호출하기 전에 함수선언이 있지않아 오류가 나야하지만 호이스팅으로 인해 해당 function 블럭이 최상단으로 끌어올려져 sayHello()가 정상적으로 실행되게된다. *코드의 가독성을 위해 변수와 함수를 사용하기 전에 선언하는 것이 우선권장된다. classList. add/remove/toggle/contains 클래스 목록 관리하기 classList.add(class1, class2, ...) 요소의 클래스 목록에 클래스를 추가, 여러 개의 클래스를 추가할 수 있습니다. classList.remove(class1, class2, ...) 요소의 클래스 목록에서 클래스를 제거, 여러 개의 클래스를 제거할 수 있습니다. classList.toggle(class, force) 요소의 클래스 목록에서 클래스를 추가하거나 제거, 클래스가 이미 존재하면 제거하고, 존재하지 않으면 추가 force 매개 변수를 사용하여 클래스를 강제로 추가 또는 제거할 수 있다. classList.contains(class) 요소의 클래스 목록에 클래스가 존재하는지 확인, true 또는 false를 반환된다. for of 과 for in의 차이 for of은 객체를 반환하고 for in는 index를 반환한다. let array1=[52, 273, 32, 93, 103] for(let element of array1){ document.write(element+" "); } document.write(" "); for(let i in array1){ document.write(array1[i]+" "); } Math.min/max 최소값, 최대값 구하기 최소값, 최대값 구하기 Math.min.apply Math.max.apply let array2 = [273, 52, 103, 57, 271]; let min=Number.MIN_VALUE; let max=Number.MAX_VALUE; min= Math.min.apply(null, array2); max= Math.max.apply(null, array2); document.write(`가장 작은 수${min}`+" "); document.write(`가장 큰 수${max}`); sort(fnc(a, b{}return a-b)) + reverse() 내림차순 sort(fnc(a, b{}return a-b)) + reverse() 내림차순 let array = [52, 71, 32, 103, 273, 93] array.sort(function (a, b) {return a - b}) document.write(array.reverse()); //273,103,93,71,52,32 https://standout.tistory.com/611 sort(fnc(a, b{}return a-b)) 오름차순 sort(fnc(a, b{}return a-b)) 오름차순 let array = [52, 71, 32, 103, 273, 93] array.sort(function (a, b) {return a - b}) document.write(array); //32,52,71,9.. sort(fnc(a, b{}return a-b)) 오름차순 sort(fnc(a, b{}return a-b)) 오름차순 let array = [52, 71, 32, 103, 273, 93] array.sort(function (a, b) {return a - b}) document.write(array); //32,52,71,93,103,273 reverse() 역순정렬 reverse() 역순정렬 let array = [52, 71, 32, 103, 273, 93] document.write(array.reverse());//93,273,103,32,71,52 자바스크립트에서 ${contextPath} 변수로 사용하기 원하는 변수값안에 아래의 함수를 적는다, 함수가 contextPath를 반환해준다. var = getContextPath() function getContextPath() { var hostIndex = location.href.indexOf( location.host ) + location.host.length; return location.href.substring( hostIndex, location.href.indexOf('/', hostIndex + 1) ); }; ajax에서 에러 처리 + 아무런 에러가 뜨지않음 ajax로 보낼 data 변수명이 맞는지, 오타는 없는지 확인해보자. ajax는 친절하게 알려주지않는다. contextPath 변수를 사용하여 action한다면 해당 변수가 설정되었는지도확인해보자. selectBox.nextSibling 오류 nextElementSibling var input = selectBox.nextSibling input.setAttribute("value", value); 위의 코드로 selectbox의 값을 input에 넣는데 작동이 되지않았다. nextElementSibling로 바꿔보자. var input = selectBox.nextElementSibling input.setAttribute("value", value); 이유는 무엇일까? nextSibling은 현재 요소의 다음 형제 노드를 반환한다. 이 속성은 텍스트 노드, 주석 노드 등 모든 노드 유형에 대해 작동한다. 무엇이라도 하나가 더 있다면 원하는 요소를 잡기 어려울 수 있다는 말이다. 반면에, nextElementSibling은 현재 요소의 다음 형제 요소를 반환한다. 이 속성은.. 자바스크립트 Node 선택자 예약어 정리, 자식/type/name/value childNodes 현재 노드의 모든 자식 노드 목록을 선택 var div = document.querySelector("div"); var childNodes = div.childNodes; hasChildNodes 현재 노드에 자식 노드가 있는지 확인 var div = document.querySelector("div"); var hasChildNodes = div.hasChildNodes(); nodeType 현재 노드의 유형을 반환 var p = document.querySelector("p"); var nodeType = p.nodeType; nodeName 현재 노드의 이름을 반환 var p = document.querySelector("p"); var nodeName = p.nodeName;.. ul 태그에 innerHTML 안됨, 쉬운해결법 main.do:56 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') console에도 잘 뜨고 div에는 innerHTML되지만 리스트 ul안에 innerHTML안되는 현상이 생겼다. div에 innerHTML이 된다면, 발상의 전환으로 ul에 div를 넣어 쉽게 해결했다. 추후 더 찾아보니 태그는 innerHTML 프로퍼티를 사용하여 내부 HTML 코드를 설정하는 것은 지원되지 않는다고 하는데.. 요소의 내용을 변경하려면 태그를 추가하거나 제거해야 한다고 한다. 이를 통해 목록 아이템을 동적으로 추가하거나 삭제할 수 있다. var myList = document.getElementById("myList"); var newI.. 자바스크립트 선택자 예약어 정리, 부모/자식/형제 가물가물할때마다 검색하는게 시간낭비 인것같아 기록해봤다. querySelector 문서 내 첫 번째 요소를 반환 document.querySelector('.class'); querySelectorAll 문서내 모든 요소 반환 document.querySelectorAll('.class'); id, class, tag 해당되는 모든 요소 반환 document.getElementById("#id") document.getElementsByClassName(".class") document.getElementsByTagName("div") name 속성값이 일치하는 모든 요소 반환 document.getElementsByName("password") children index 자식 선택자 label.chil.. 자바스크립트 input files 이름 불러오기 const file_real = document.querySelector('.file_real'); let files = file_real.files[0].name; https://standout.tistory.com/404 자바스크립트 file input 커스텀, placeholder/value 지정하기 file를 커스텀해보자. file input과 readonly input을 label로 묶어 구현한다. 첨부하기 function filesToFackFilesInput(label){ let file_real = label.children[0]; let file_fake = label.children[1]; file_real.addEventListener("change", functio standout... 자바스크립트 file input 커스텀, placeholder/value 지정하기 file를 커스텀해보자. file input과 readonly input을 label로 묶어 구현한다. 첨부하기 function filesToFackFilesInput(label){ let file_real = label.children[0]; let file_fake = label.children[1]; file_real.addEventListener("change", function () { let files = this.files[0].name; console.log(files); file_fake.value = files; }); } 이후 .file_real을 display-none해주면 완료. span태그와 css를 추가해 기존에 기획했던 디자인과 통일해보자. 아래의 main.png가 value.. 자바스크립트 alert 한번만 띄우게하기 alert을 띄운뒤, 변수값을 false로 바꾸고, alert을 if문으로 감싸자. if, 조건이 false이라면 if문은 실행되지않는다. var showAlert = true; function showAlertOnce() { if (showAlert) { alert("안녕하세요!"); showAlert = false; } } 오로라 그라데이션 javascript code jquery 연결 원하는영역을 잡는다. element생성 스크립트 추가, 끝. color는 rgb값으로 자유롭게 변경한다. 이전 1 2 다음