두둥 다시 돌아온 form 태그 !!

[form객체 얻는 방법]
ex)
form의 하위 객체로
아이디: <input type="text" name="choi"/>

※form객체를 이용해서 form의 하위객체 얻기
원칙) form객체.name속성에 지정한 값 : form객체.choi

1. <form> : form에 id및 name속성 지정 안한 경우
-document.forms(HTMLCollection) 이용
ex. 해당 HTML문서에서 첫번째 (유사배열)
form태그인 경우 : document.forms[0].choi

2. <form name="폼이름"> : form에 name속성 지정한 경우(가장 코드가 짧고 많이 씀)
-바로 폼이름이 form객체가 됨
<form name="frmObj">
ex.폼이름.name속성에 지정한 값
frmObj.choi

3. <form id="id명"> : form에 id속성 지정한 경우
- document.getElementById("id명").choi
혹은
document.querySelector("#id명").choi

4. document객체의 getElementsByTagName("form")[인덱스].choi
혹은
getElementsByName("폼이름")[인덱스].choi

5. this.form키워드로 form객체를 얻어 올 수 있다.
<input type="button" onclick = "fnSubmit(this.form)"/>

****※자바스크립트 코드로 submit시 submit이벤트는 발생하지 않는다****
ex) form객체.submit( ); 단순히 함수를 호출한다고 해서 이벤트는 발생 안해 .. 전송만 됨


얻어온 HTML가.. 길다... 근데 submit 기능이 있는 버튼 없는 버튼등 모든 경우를 다 처리 해 줘야 한다 !!

 <h2 name="h2Obj" id="h2Id">회원가입 페이지</h2>
  <!--방법1]submit기능이 있는 버튼으로 전송시-->
  <!--
  <form name="formObj" id=formId action="http://www.google.co.kr" method="get" onsubmit="return isValidate();">
-->
 <!-- 
    <form name="formObj" action="http://www.google.co.kr">
           -->

  <!-- 방법2]submit기능이 없는 버튼으로 전송시 -->
  <form name="formObj" action="http://www.nate.com" onsubmit="alert('submit이벤트 발생');">

    <table style="width:600px;border-spacing:1px;background-color:green">
          <tr style="background-color:white">
              <td  style="width:15%">아이디</td>
              <td><input type="text" name="id" size="20" /> <span style="color:red;font-size:0.8em" id="idError"></span></td>
          </tr>
          <tr style="background-color:white">
              <td>비밀번호</td>
              <td><input type="password" name="pwd" size="20" /></td>
          </tr>
          <tr style="background-color:white">
              <td>비밀번호확인</td>
              <td><input type="password" name="pwd2" id="pwd2" size="20" /></td>
          </tr>
          <tr style="background-color:white">
              <td>성별</td>
              <td>
                  <input type="radio" name="gender" value="man" />남
                  <input type="radio" name="gender" value="woman" />녀
                  <input type="radio" name="gender" value="trans" />트랜스젠더
              </td>
          </tr>
          <tr style="background-color:white">
              <td>관심사항</td>
              <td>
                  <input type="checkbox" name="inter" value="pol" />정치
                  <input type="checkbox" name="inter" value="eco" />경제
                  <input type="checkbox" name="inter" value="spo" />스포츠
                  <input type="checkbox" name="inter" value="ent" />연예
              </td>
          </tr>
          <tr style="background-color:white">
              <td>학력사항</td>
              <td>
                  <select name="grade">
                      <option value="">==학력을 선택하세요==</option>
                      <option value="ele">초등학교</option>
                      <option value="mid">중학교</option>
                      <option value="hig">고등학교</option>
                      <option value="uni">대학교</option>
                  </select>
              </td>
          </tr>
          <tr style="background-color:white">
              <td>첨부파일</td>
              <td>
                  <input type="file" name="file" size="40" />
              </td>
          </tr>
          <tr style="background-color:white">
              <td>자기소개</td>
              <td>
                  <textarea cols="60" rows="5" name="self"></textarea>
              </td>
          </tr>
          <tr style="background-color:white">
              <td colspan="2" align="center">
                  <table>
                      <!-- 방법1:submit기능이 있는 폼 하위태그-->
                      <tr>
                          <td>
                              <input type="submit" style="height:50px" value="submit버튼" title="type=submit" />
                          </td>
                          <td>
                              <input type="image" src="../HTML5/Images/submit1.png" title="type=image"
                                  alt="image버튼" />
                          </td>
                          
                          
                          <td>
                              <!--방법2:submit기능이 없는 태그로 전송-->
                              <input type="button" onclick="fnNoSubmitButton(this.form);"  style="height:50px"   value="submit기능이없는 버튼" />
                          </td>
                          <td>
                              <a href="#" onclick="fnNoSubmitButton(this.form);">
                                  <img style="height:100%"  src="../HTML5/Images/submit2.png" alt="이미지태그1"
                                      title="a태그로 링크주고 a태그에 리스너 부착" />
                              </a>
                          </td>
                          <td>    <!-----  cursor:pointer 이거는 마우스를 손모양으로 바꾸게 하는 것 !!!--->
                              <img style="cursor:pointer" onclick="fnNoSubmitButton(this.form);"
                                  src="../HTML5/Images/submit3.png" alt="이미지태그2" title="img태그에 직접 리스너 부착" />
                          </td>
                      </tr>
                  </table>
              </td>
          </tr>
      </table>
  </form>



form 요소는 name속성으로 노드접근 가능 , 다른요소는(태그)는 불가
모든 요소(태그)의 id속성으로 해당노드 접근 가능(아이디는 유일하니까 가능 )
dom api로 노드 얻자 !
console.log('h2Obj:',h2Obj; // h2 is not defined ! h2는 폼 요소 아님
console.log('formObj:',formObj); //폼 노드 얻어옴(폼)
console.log('h2Id:',h2Id); // h2노드 잘 얻어옴(id속성)
console.log('formId:',formId); // 얘도(폼+id)

h2는 폼 요소가 아니라 name속성으로 노드 접근 불가
다른건 모두 노드 얻어올 수 있다 !!


이제 이벤트처리 해보자 !!

   window.addEventListener('DOMContentLoaded',function(){
           //방법1. onsubmit속성으로 이벤트 처리        
       formObj.onsubmit = isValidate;  // 이건 return false로 이벤트 취소 가능
            //방법2. addEventListener으로 이벤트 처리  
       formObj.addEventListener('submit',isValidate);  // 이건 e.preventDefault()로 이벤트 취소 가능            
   });
   
   		// 위에선 함수만 선언하고 함수정의는 밑에서 함 ! 이렇게 떼낼 수 도 있구나
        // 함수 선언 할 때는 () 안붙인다 !! ()붙이면 호출이지
   
    function isValidate(e){  // 태그 return false하면 전달 x
            console.log('이벤트객체(e):',e);  //찍어봐 뭐가 처리가 안되었는지 알 수 있음!
            
               //1. 아이디 처리
            if(formObj.id.value.trim()===''){
                alert('아이디를 입력하세요');                
                formObj.id.focus();
                if(e !== undefined ) 
                e.preventDefault();  // addeventlistener()로 이벤트 처리 시 submit 취소         
                return false;        // 어떤 버튼을 누를 지 모르니 둘다 처리 해야한다.
            }
 			
              //2. 비밀번호 처리
          if(formObj.pwd2.value.trim().length===0){
                alert('비밀번호 확인을 입력하세요');                
                formObj.pwd2.focus();
                if(e !== undefined ) 
                e.preventDefault(); 
                return false;
          }
			//비밀번호 일치 여부 처리
		  else{
               if(formObj.pwd.value.trim()!== formObj.pwd2.value.trim()){
                  alert('비밀번호가 일치하지 않습니디.');                
                  formObj.pwd2.focus();
                    if(e !== undefined ) 
                     e.preventDefault(); 
                     return false;
               }
          }
          
            //성별 처리
            //라디오 버튼 선택여부 판단, 체크박스나 라디오버튼은 radionodeList타입 유사배열
            var isGender = false;
            formObj.gender.forEach(function(item){  //일반for문도 사용 가능!!
                if(item.checked){
                   isGender=true;
                }
            });
			if(!isGender){
                alert('성별을 선택하세요');                
                formObj.gender[0].focus();
                   if(e !== undefined ) 
                   e.preventDefault(); 
                   return false;
            }
            
            //문) 관심사항 체크박스는 최소 3개이상 선택하게 하고 아니면 이벤트 취소 처리하라.
             var isinter=[];   // 나는 배열로 처리했는데 count로 처리해도 됨!
             formObj.inter.forEach(function(item){
                if(item.checked){isinter.push(item);}                 
            })
            if(isinter.length <3 ){
                 alert('3이상 선택하세요');   
                 if(e !== undefined ) 
                   e.preventDefault();              
                   return false;
            }

              //학력사항 처리
            if(formObj.grade.selectedIndex ===0 ){
                alert('학력사항을 선택하세요');                
                formObj.grade[0].focus();
                  if(e !== undefined ) 
                    e.preventDefault(); 
                    return false;
            }

              //파일로드 처리
            if(formObj.file.value.trim()===''){
                alert('파일을 입력하세요');                
                formObj.file.focus();
                  if(e !== undefined ) e.preventDefault(); 
                  return false;
            }
            
             //자기소개 처리
            if(formObj.self.value.trim()===''){
                alert('자기소개를 입력하세요');                
                formObj.self.focus();
                  if(e !== undefined ) e.preventDefault(); 
                  return false;
            }
               return true;            
     }////isValidate
     
     		function fnNoSubmitButton(obj){ // submit기능이 없는 버튼으로 전송했을 때
            console.log(obj);  // 처음것만 반응하고 나머지는 undefined
               if(obj === undefined)   //obj가 폼 객체가 아닐 때
                 obj=document.forms[0];   //폼 태그가 1개밖에 엄슴
                //form 객체의 submit함수로 호출 하지만... 이벤트 호출은 발생 안 됨 
               if(isValidate()) obj.submit();
            };


++추가
성별 체크 시
일반 for문 사용은
var isGender = false;
for(var i=0 ; i< formObj.gender.length ; i++){
if( formObj.gender[i].checked){
isGender = ture;
break;
}
}
쉬워용

그리고 관심사항 count 버전
체크박스 3개 이상 선택하도록 유효성 검사
var count=0;
formObj.inter.forEach(function(item){
if(item.checked) count++;
});
if(count < 3){
alert('관심사항은 3개이상 선택하세요');
formObj.inter[0].focus();
if(e !== undefined) e.preventDefault(); //addEventListener()로 submit이벤트 처리 시
return false;
}

 

 style="cursor:pointer" 이거는 마우스를올렸을 때 커서모양을 손모양으로 바꾸게 하는 것 !!!


++추가
e !==undefined 기능을 잘 몰라서 실험해봄

아이디 넣었는데도 submit 기능이 없는 버튼을 누르면 전송 안됨!! 이벤트객체가 undefined 라고 콘솔창에 뜸
이거 분명... basic 때 확인 한거 같은데.... 다시 봐도 잘 모르겟으니 우선 패스....
뒤에 배우다 보면 분명 이해 될거야 ...

submit1.png
0.00MB
submit2.png
0.00MB
submit3.png
0.00MB

FormObject22.html

회원가입 페이지

아이디
비밀번호
비밀번호확인
성별 트랜스젠더
관심사항 정치 경제 스포츠 연예
학력사항
첨부파일
자기소개
이미지태그1 이미지태그2

'학원 > JS' 카테고리의 다른 글

11/09 39-4 [JS] InnerXXXTextContent  (0) 2022.11.09
11/09 39-3 [JS] MouseEvent  (0) 2022.11.09
11/09 39-2 [JS] FocusEvent  (0) 2022.11.09
11/09 39-1 [JS] KeyboardEvent  (0) 2022.11.09
11/08 38-8 [JS] CSSControl  (0) 2022.11.08

시작태그와 종료태그가 있는 모든 태그들은

innerHTML과 innerText 및 textContent속성을 갖고 있다.

이 세개는 기능이 비슷하면서도 조금씩 다름! 그걸 비교해서 각각 필요할 때 사용 하면 됨!!
(<input /> ,<br/>나 <img/>등은 제외  - 얘네는 종료태그가 없으)
      
시작태그와 종료태그 사이의 컨텐츠가 inner계열 속성 및 textContent에 저장됨.
      
시작태그와 종료 태그 사이에 태그요소가 있는 경우
      innerHTML:태그 요소를 실행
      innerText 와 textContent : 태그요소를 제외한 순수 텍스트만 저장
시작태그와 종료 태그 사이에 빈 공백이 많은 경우
      innerHTML 와 textContent:빈 공백 그대로를 저장
      innerText : 빈 공백 제외

 

가져온 HTML

  <h2 id="h2">inner계열 및 textContent속성</h2>
  <input type="button" value="시작태그와 종료태그사이에 있는값 얻기" />
  <input type="button" value="innerHTML"  />
  <input type="button" value="innerText" />
  <input type="button" value="textContent" />
  <span id="span">텍스트</span>
 
  <p>
    HELLO

    JAVASCRIPT
  </p>

 

1. 필요한 요소 가져오기

var h2 = document.querySelector('#h2';);

var span = document.querySelector('span');

var p = document.querySelector('p');

 

2. 첫 번째 버튼 클릭 시 콘솔창에 h2태그 사이에 있는 텍스트 출력(각각의 속성 모두 사용)

 document.querySelector(''input:nth-child(2)'').onclick = function(){  // input의 부모(body)요소 중 2번째 자식요소

         console.log(h2.innerText);
         console.log(h2.innerHTML);
         console.log(h2.textContent);
 };

콘솔 결과

 

3.두 번째 버튼 클릭 시 span태그에 있는 글자를 두껍게하는 HTML 적용

  document.querySelector('input:nth-child(3)').onclick = function(){

      span.innerHTML='<strong>컨텐츠 설정:innerHTML</strong>';

};

 

4.세 번째 버튼 클릭 시 span태그에 있는 글자를 두껍게하는 HTML 적용(innerText 사용)

  document.querySelector('input:nth-child(4)').onclick=function(){
       span.innerText='<strong>컨텐츠 설정:innerText</strong>';

 };

 

5.네 번째 버튼 클릭 시 span태그에 있는  글자를 두껍게하는 HTML 적용(textContent 사용)

    document.querySelector('input:nth-child(5)').onclick=function(){
     span.textContent='<strong>컨텐츠 설정:textContent</strong>';
};

 

6.각각의 속성들이  공백처리 하는 법 비교 

    console.log('-------------p.innerHTML-----------');
    console.log(p.innerHTML);
    console.log('-------------p.innerText-----------');
    console.log(p.innerText);   // 콘솔 창을 보면 공백 제거할 땐 요놈 가져오는게 유리하겠다고 생각 듦
    console.log('-------------p.textContent---------');
    console.log(p.textContent);

 

innerText 가 공백제거시 유리

'학원 > JS' 카테고리의 다른 글

11/09 39-5 [JS] FormObject  (1) 2022.11.09
11/09 39-3 [JS] MouseEvent  (0) 2022.11.09
11/09 39-2 [JS] FocusEvent  (0) 2022.11.09
11/09 39-1 [JS] KeyboardEvent  (0) 2022.11.09
11/08 38-8 [JS] CSSControl  (0) 2022.11.08

[마우스 이벤트]
mousedown:태그영역에서 마우스 다운 시(클릭을 눌렀을 때)
mouseup:마우스 뗐을 때
mouseover:영역에 마우스가 들어 왔을 때
mouseout:영역에서 마우스가 나갔을 때

 

받은 HTML문서

  <fieldset>
        <legend id="legend">mousedown 및 mouseup이벤트(scale 및 색상변경)</legend>
        <div style="background-color:red;width:100px;height:100px"></div>
    </fieldset>
    <fieldset>
        <legend>mousedown 이벤트(위치이동)</legend>
        <div style="position:relative;left:0;top:0;background-color:red;width:100px;height:100px"></div>
    </fieldset>
    <fieldset>
        <legend>mouseover 및 mouseout이벤트</legend>
        <h4>테이블에 적용</h4>
        <table style="border-spacing:1px;background-color:gray;width:400px">
            <tr style="background-color:white">
                <th>번호</th>
                <th>제목</th>
                <th>작성자</th>
            </tr>
            <tr onmouseover="this.style.backgroundColor='green';" onmouseout="this.style.backgroundColor='white';"
                style="background-color:white">
                <td>1</td>
                <td>제목1입니다</td>
                <td>작성자1</td>
            </tr>
            <tr onmouseover="this.style.backgroundColor='green';" onmouseout="this.style.backgroundColor='white';"
                style="background-color:white">
                <td>2</td>
                <td>제목2입니다</td>
                <td>작성자2</td>
            </tr>
            <tr onmouseover="this.style.backgroundColor='green';" onmouseout="this.style.backgroundColor='white';"
                style="background-color:white">
                <td>3</td>
                <td>제목3입니다</td>
                <td>작성자3</td>
            </tr>
        </table>
        <h4>이미지에 적용</h4>
          <img src="../HTML5/Images/1.jpg" alt="이미지" style="width:80px;height:60px;" />
    </fieldset>

 

 

 


//1. 마우스 클릭했을 때 색상 변경하기
window.addEventListener('DOMContentLoaded',function(){  //전체적으로 로드 이벤트 !
	//얻어오기
	var legend=document.querySelector('#legend');
    var div1=document.querySelector('fieldset:nth-child(1)>div');
    var div2=document.querySelector('fieldset:nth-child(2)>div')
    
    //지금 적용 되어있는 도형의 높이와 사이즈 ! 나중에 크기 변환할 때 사용 할 수 있다!
     var width=parseInt(div1.style.width);  
     var height=parseInt(div1.style.height);
     var bgcolor=div1.style.backgroundColor;

	//마우스이벤트 입히기
    //1-1.마우스 다운
    div1.onmousedown=function(e){
    	 console.log('mousedown 이벤트 발생');
           // 클릭 시 글씨도 변경
         legend.textContent='mousedown이벤트 발생' 
   		  //배경색 변경하고 스케일 2배, 여기서의 this는 이벤트가 발생한 객체(=e.target)
         this.style.backgroundColor='green';
         this.style.width=width*2+'px';
         this.style.height=height*2+'px';
    }
    
    //1-2.마우스 업
    div1.onmousup=function(e){
     	 console.log('mouseup 이벤트 발생');
         legend.textContent='mouseup이벤트 발생';
    	   //원래의 배경색 & 스케일로 변경
         this.style.backgroundColor='red';
         this.style.width=width+'px';
         this.style.height=height+'px';
    }
    
     //2.  0.3초마다 위치 이동시키기(5번)
      var count=0;
      div2.onmousedown=function(){
          console.log(this);     //여기서 this는 mousedown이 발생 한 div2 객체
          var timer = window.setInterval(function(){  
               console.log(this);       //여기서this는 window 객체                      
               var left = parseInt(div2.style.left);
               div2.style.left=left+50+'px';              
                count++;
               if(count === 5){
                      clearInterval(timer);
                       count=0;
                }                               
           },300);     // 0.3초마다 발생                                 
      };
 
 	  /* 문제 마우스오버 시에서 2.jpg로 교체
       마우스 아웃 시 다시1
       마우스 다운 시 현 이미지x2
       마우스 업 다시 원래*/
       
       var img =document.querySelector('img');
       var imgWidth = parseInt(img.style.width)
       var imgHeight = parseInt(img.style.height)
       
       img.onmouseover = function(){
  		  this.src="../HTML5/Images/2.jpg";    
       }	
       img.onmousedown = function(){
       	   this.src="../HTML5/Images/1.jpg";
       }
       img.onmousedown = function(){
       		this.style.width=imgWidt*2+'px'
            this.style.height=imgHeight*2+'px'
       }
       img.onmouseup = function(){
       		this.style.width=imgWidth+'px'
       }
})

1.jpg
0.20MB
2.jpg
0.20MB

mousedown 및 mouseup이벤트(scale 및 색상변경)
mousedown 이벤트(위치이동)
mouseover 및 mouseout이벤트

테이블에 적용

번호 제목 작성자
1 제목1입니다 작성자1
2 제목2입니다 작성자2
3 제목3입니다 작성자3

이미지에 적용

이미지

 

'학원 > JS' 카테고리의 다른 글

11/09 39-5 [JS] FormObject  (1) 2022.11.09
11/09 39-4 [JS] InnerXXXTextContent  (0) 2022.11.09
11/09 39-2 [JS] FocusEvent  (0) 2022.11.09
11/09 39-1 [JS] KeyboardEvent  (0) 2022.11.09
11/08 38-8 [JS] CSSControl  (0) 2022.11.08

포커스 관련 이벤트
        focus:포커스(커서)를 얻었을 발생하는 이벤트(리스너:onfocus)
        blur:포커스(커서)를 잃었을때 발생하는 이벤트(리스너:onblur)

 

받은 HTML문서

 <fieldset>
        <legend>focus 및 blur이벤트</legend>
        <input type="text" onfocus="console.log('focus이벤트 발생:포커스를 얻었을때')" onblur="console.log('blur이벤트 발생:포커스를 잃었을때')" />
    </fieldset>
    <fieldset>
        <legend>focus 및 blur이벤트 예제(HTML5의 속성 이용-IE에서만 적용됨)</legend>
        아이디 <input type="text" placeholder="아이디" />
        비밀번호 <input type="password" placeholder="비밀번호" />
    </fieldset>
    <fieldset>
        <legend>focus 및 blur이벤트 예제(자바스크립트로 구현)</legend>
        아이디 <input type="text" value="아이디" style="color:lightgray"  />
        비밀번호 <input type="text" value="비밀번호" id="txt" style="color:lightgray"/><input type="password" id="pwd" style="display:none"/>
    </fieldset>

 

새로생긴 CSS속성 중 placeholder가 없었을 땐 자바스크립트로 모두 구현 했어야 했다고 함

그걸 해볼 것임 

아...

내가만든 placeholder

window.addEventListener('DOMContentLoaded',function(){
	var username= document.querySelector('fieldset:nth-child(3)>[type=text]:nth-child(2)')
	console.log(username)

	//아이디처리
	username.onfocus=function(){  //입력 시 처리
		if(this.value === '아이디'){
		this.value='';
    	this.style.color='black';
 		}
	};
    
    username.onblur=function(){   //입력 없고 포커스 잃었을 때
    	if(this.value.trim().length==0){
        this.value='아이디';
        this.sytle.color='lightgray';
        }
    };



   //비밀번호 처리
  		var txt = document.querySelector('#txt');
        var pwd = document.querySelector('#pwd');
         //type="text"에는 onfocus 리스너 부착
        txt.onfocus=function(){
            txt.style.display='none';
            pwd.style.display='';
            pwd.focus();
        };
          //type="password"에는 onblur 리스너 부착
        pwd.onblur = function(){
            if(pwd.value.trim()==''){
                pwd.style.display='none';
                txt.style.display='';
            }
        }

});
focus 및 blur이벤트
focus 및 blur이벤트 예제(HTML5의 속성 이용-IE에서만 적용됨) 아이디 비밀번호
focus 및 blur이벤트 예제(자바스크립트로 구현) 아이디 비밀번호

 

'학원 > JS' 카테고리의 다른 글

11/09 39-4 [JS] InnerXXXTextContent  (0) 2022.11.09
11/09 39-3 [JS] MouseEvent  (0) 2022.11.09
11/09 39-1 [JS] KeyboardEvent  (0) 2022.11.09
11/08 38-8 [JS] CSSControl  (0) 2022.11.08
11/08 38-7 [JS] EventTrigger  (0) 2022.11.08

키보드 이벤트 : 텍스트상자( <input type="text"~ >    또는    <input type="password"  ~>등 ) 
        입력상자에서 적용되는 이벤트
        keydown:"모든 키"를 누를 때 발생하는 이벤트
        keyup:키보드를 뗄 때 발생하는 이벤트
        keypress:"문자 키"를 누를 때 발생하는 이벤트(방향키나 DELETE키,한글 누를 때는 발생안함-FIREFOX에서만 적용안됨)

 

 

받은 HTML

   <fieldset>
        <legend>key이벤트 테스트</legend>
        keydown: <input type="text" />
        keyup: <input type="text" onkeyup="fnKeyHandler(1)" />
        keypress: <input type="text" onkeypress="fnKeyHandler(2)" />
    </fieldset>
    <fieldset>
        <legend>주민번호</legend>
        <input type="text"  size="6" maxlength="6" onkeyup="fnSetFocus(this)" />
        -
        <input type="text" size="7" maxlength="7" id="ssn" />
    </fieldset>

 

이벤트 객체 확인 먼저 해봄

//확인용 코드
window.addEventListener('DOMContentLoaded',function(){
	var input = document,querySelector('input');
    input.onkeydown = function(e){
 		console.log('keydown이벤트 발생');
        console.log('이벤트명:',e.type);
        console.log('e.key:',e.key);
        console.log('e.keyCode:',e.keyCode);
        console.log('e.code:',e.code);
        console.log('ENTER' === e.key.toUpperCase());  // 엔터일때 
        console.log( 13 === e.keyCode);  // 이게 더 낫겟음

        if(13 === e.keyCode){   // this는 e.target과 같다.
        console.log('입력한 문자열:',this.value); // 이거나 input.value 랑 같음 ! 
        }                       
    };
});

===> 키보드 5 입력 시 출력

 

 
 // 보낸 HTML파일에서 보면 같은 함수인데 인자만 다르게 해서 리턴값이 다르게 나오게 함 
 function fnKeyHandler(flag){
 		switch(flag){   // swich문으로 나눠줌 
        	case 1: console.log('keyup 이벤트 발생'); break;   //키보드 뗐을 때
            default : console.log('keypress이벤트 발생');     //키보드 누르고 있을 때
        }
 }

//주민번호 앞에 6자리 누르면 바로 뒷 자리 입력할 수 있기 focus 이동 하기 !! 
 function fnSetFocus(obj){
 	 if(obj.value.length == 6 ) document.querySelector('ssn').focus()
 }
key이벤트 테스트 keydown: keyup: keypress:
주민번호 -

'학원 > JS' 카테고리의 다른 글

11/09 39-3 [JS] MouseEvent  (0) 2022.11.09
11/09 39-2 [JS] FocusEvent  (0) 2022.11.09
11/08 38-8 [JS] CSSControl  (0) 2022.11.08
11/08 38-7 [JS] EventTrigger  (0) 2022.11.08
11/07 37-3 [JS] EventBubbling  (0) 2022.11.07

[자바스크립트로 CSS제어하기]
방법1)
엘리먼트객체.style.CSS속성="CSS속성값";
단, CSS속성을 자바스크립트로 표현할때는 -(DASH)가 빠지고 두 번째 글자의 첫 글자가 대문자로 바뀜.
-가 없는 CSS속성인 경우 그냥 소문자로 접근하면 됨
방법2)
엘리먼트객체.style["CSS속성"]="CSS속성값";
이때는 CSS속성 그대로 넣어준다( - 이거넣어줘야함)
ex)
css코드
font-size:10pt(CSS);
color:red(CSS);
background-image:url(이미지경로);

위 css코드를 자바스크립트로 표현
객체.style.fontSize="10pt";(자바스크립트)
객체.style["font-size"]="10pt";(자바스크립트)
객체.style.color='red';(자바스크립트)
객체.style["color"]='red';(자바스크립트)
객체.style.backgroundImage ="url('이미지경로')";
객체.style["background-image"] ="url('이미지경로')";

문제) 다음 문서를 자바스크립트로 구현 해 보세요 !!!!!

<h2 style="color:red ;" >자바스크립트로 CSS제어하기</h2>
  <span id="span">SPAN태그</span>
  <input type="button" value="글꼴바꾸기" />
 
  <fieldset>
      <legend>신문기사</legend>
      <button >+</button>
      <button >-</button>
      <button >Red</button>
      <button >Green</button>
      <button >Blue</button>
      <button >Black</button>
      <button >볼드체</button>
      <button >보통</button>
      <p style="font-size:10px;" id="article">
          박 대통령은 이날 청와대에서 열린 대통령 주재 수석비서관회의에<br />
          참석해 이 같이 밝히며 “각 수석들은 국민을 대신해 일하고<br />
          있는 분들인 만큼, 국민을 위해서 잘못된 그 어떤 것들에도<br />
          결코 굴복하거나 용인하지 않겠다는 강한 의지를 가지고<br />
          일해주길 바란다”고 당부했다.<br />
      </p>
  </fieldset>
window.addEventListener('DOMContentLoaded',function(){
		//가져올 것 가져와
        var span = document.querySelector('#span');
        var h2 =document.querySelector('h2');
        
        document.querySelector('[type=button]').onclick=function(){
          // 이렇게 쓸 수도 있고
          span.style.color='red';
          span.style.fontWeight='bold';
          //이렇게 쓸 수도 있음
          span.style['color']='green';
          span.style['font-weight']='bold';
          // 배경도 넣을 수도 있음
         h2.style.backgroundImage="url(../HTML5/Images/1.jpg)";         
        };
        
        //가져올거 마져 가져옴
        var fieldset = document.querySelector('fieldset');     
        var p = document.querySelector('#article');
        
        
        fieldset.onclick = function(e){   // 이벤트 버블링 해줌 !
           if(e.target.nodeName !== 'BUTTON') return;  // 버튼만 클릭 할 때로 제한
           console.log(parseInt(p.style.fontSize));  //찍어 보고 폰트크기는 숫자니까 parseInt !
           var currSize=parseInt(p.style.fontSize);   //변수로 담아주고
  		   switch(e.target.textContent.trim()){    // button 태그들을 나눠서 달아줍니다.
            	case '+': currSize += 5;
                          p.style.fontSize=currSize+'px';  
                    break;
                case '-': if(currSize >= 10 ) 
                          currSize -= 5;
                          p.style.fontSize=currSize+'px';  
                    break;
                case 'Red':p.style.color='red';   
                    break;
                case 'Green':p.style.color='green';  
                    break;
                case 'Blue':p.style.color='blue';  
                    break;
                case 'Black':p.style.color='black';  
                    break; 
                case '볼드체':p.style.fontWeight='bold';   
                    break;  
                default :p.style.fontWeight='normal';                                    
             }    
        };
});
CSSControl17.html

자바스크립트로 CSS제어하기

SPAN태그
신문기사

박 대통령은 이날 청와대에서 열린 대통령 주재 수석비서관회의에
참석해 이 같이 밝히며 “각 수석들은 국민을 대신해 일하고
있는 분들인 만큼, 국민을 위해서 잘못된 그 어떤 것들에도
결코 굴복하거나 용인하지 않겠다는 강한 의지를 가지고
일해주길 바란다”고 당부했다.

 

'학원 > JS' 카테고리의 다른 글

11/09 39-2 [JS] FocusEvent  (0) 2022.11.09
11/09 39-1 [JS] KeyboardEvent  (0) 2022.11.09
11/08 38-7 [JS] EventTrigger  (0) 2022.11.08
11/07 37-3 [JS] EventBubbling  (0) 2022.11.07
11/07 37-3 [JS] EventBasic  (0) 2022.11.07

어? 트리거다 

오라클 트리거?

개념은 비슷하지만 그거보단 조금은 덜 복잡함 !

 

대충 목적은 이런것

브라우저마다 기본제공해주는 것들 예를들면 브라우저창 모양이라던가 클릭하는 버튼모양이라던가 

스타일이 다 다르기도 하고 기본이라서 디자인이 이쁘지 않음

내가만든 홈페이지나 프로그램은 어떤 브라우저를 쓰든 동일한 아이콘을 보여주고 싶고 기본보다 이쁘게 꾸미고 싶을 때 이벤트 트리거를 쓴다 

 

작동원리는 이런 것

어쨌든 브라우저에서 제공해주는 기본 요소들은 아예 없앨 수 없음

그럼 요소들을 겉으로 보이지 않게 숨기고 내가 만든 아이콘만 보이게 한 다음 요소들에 트리거를 걸어서 내 아이콘과 연결 시키면 됨 ! 

 

저기 저 빨갛게 표시한거 없애고 기능만 내 아이콘에다 붙이고 싶을 때 사용 !!

 

우선 받은 HTML 문서  여기서 저 위에 그림처럼 보이는 찾아보기.. 버튼은 hidden 속성으로 숨겨버린다!!

 <div class="container-fluid">
        <fieldset>
          <legend>이벤트 트리거</legend>
          <!--브라우저마다 모양이 다르다-->
          <input type="file" hidden/>
           <!--아래는 브라우저마다 모양이 동일하다(즉 아래 UI로 type="file"효과내기)-->
          <form class="form-inline">
            <div class="form-group">
              <input type="text" class="form-control">
            </div>
            <button type="button" class="btn btn-success ml-2">파일찾기</button>
          </form>
        </fieldset>
      </div>

 

 

트리거 해보자!!

//버튼이벤트 입히기
window.addEventListener('DOMContentLoaded',function(){
	var file = document.querySelector('[type=file]');   // 기본파일요소
    var button = document.querySelector('[type=button]'); // 내가만든 버튼아이콘
    var text = document.querySelector('[type=text]');   // 파일로드 되면 표시될 파일명.확장자 등..
	// 버튼 클릭 시 type='file'요소에 클릭 이벤트가 발생하도록 트리거 걸기
    button.onclick = function(){
    	var fileClick = new MouseEvent('click',{   // 이거 신기하네....
			bubbles:true,        
        	cancelable:true,
            viw:window
        })
        //type="file"요소에 마우스 클릭 이벤트 발송
        file.dispatchEvent(fileClick);   // fileClick이라는 내가만든 함수에 이벤트를 발생시키는 메소드래!
    };
    file.onchange=function(e){
    	console.log('파일선택완료',file.value)
        var path = file.value.split('\\');   var path = file.value.split('\\');  // 찍어보면 Array(3) [ "C:", "fakepath", "3.jpg" ] 여기서 이름만 가져오는거 !
        text.value = path[path.length-1];
    }   
})

 

EventTrigger16.html
이벤트 트리거

 우메..... 여기선 구현이 안된다 .. 짜아아아아증 

'학원 > JS' 카테고리의 다른 글

11/09 39-1 [JS] KeyboardEvent  (0) 2022.11.09
11/08 38-8 [JS] CSSControl  (0) 2022.11.08
11/07 37-3 [JS] EventBubbling  (0) 2022.11.07
11/07 37-3 [JS] EventBasic  (0) 2022.11.07
11/07 37-3 [JS] Date  (0) 2022.11.07

 

받은 HTML

이벤트 버블링을 이용한 이벤트 처리 풍경 첫번째 풍경 두번째 풍경 세번째 풍경 네번째
큰 풍경
이벤트 버블링 막기 즉 부모로 전파되는 이벤트 막기 REPLACE

이벤트 버블링 : 이벤트가 부모로 전파되는 방식.  기본 방식이다(디폴트값)

(이벤트 캡쳐링은 반대임 부모에서 자식으로 내려옴)
이벤트 캡처링 방식을 사용하려면

addEventListener("이벤트명", 콜백함수, useCapture);


useCapture를  true 로 설정하면 해당 객체에는 이벤트 캡처링방식으로 이벤트가 전파된다
즉 이벤트 버블링과 캡처링은 조상-자손 관계를 가진 두 개의 요소가 동일한 이벤트에 대한 리스너를 가지고 있을 때, 두 요소에 이벤트가 전파되는 방법을 말한다.

이벤트 전파 모드에 따라 두 요소 중 이벤트를 먼저 수신하는 쪽이 달라진다
  그림참고 : https://www.w3.org/TR/DOM-Level-3-Events/#event-flow
 

후려쳐서
    ex> 부모가 1 자식이 10 개인데 클릭이벤트를 10개의 자식에게 일일이 다 부착하는거 보다
    부모한테 리스너를 한 번 부착하는게 더 간단함 ! 이거 하는게 버블링

 

버블링방식(false)  
  window.addEventListener('DOMContentLoaded',function(){
        var body = document.querySelector('body');
        var fieldset = document.querySelector('fieldset');
        var img = document.querySelector('img');
        
    window.addEventListener('click',function(){
            console.log('Window에 클릭이벤트 발생');           
        },true)
    document.addEventListener('click',function(){
            console.log('Document에 클릭이벤트 발생');           
        },true)
    body.addEventListener('click',function(){
            console.log('body에 클릭이벤트 발생');           
        },true)
    fieldset.addEventListener('click',function(){
            console.log('fieldset에 클릭이벤트 발생');           
        },true)
    img.addEventListener('click',function(){
            console.log('img에 클릭이벤트 발생');           
  },false) 요기서 true 로 바꾸면 캡처링으로 바뀜

 

    이벤트 버블링 미 적용 시 :순회하면서 모든 img요소에 click이벤트 리스너 부착 .이건 매우 비효율적
    이벤트 버블링 적용 시 : 모든 이미지 요소에 바인딩 할 필요 없이 부모 요소에 한 번만 이벤트를 바인딩 하면 된다.

 

window.addEventListener('DOMContentLoaded',function(){
      var smalls = document.querySelectorAll('.small');
      var big = document.querySelector('.big');
              //이벤트 버블링 미 적용 시
           smalls.forEach(function(img){
             img.onclick=function(){
                console.log(img.src);
                //작은 이미지 클릭 시 큰 이미지를 작은 이미지로 교체
                big.src=img.src;
            };
          }); 

             //이벤트 버블링 적용 시 
      var fieldset = document.querySelector('fieldset');
        fieldset.onclick = function(e){
            console.log('클릭 이벤트 발생');
            console.log("e.target:",e.target)       //target은 이벤트가 발생한 객체를 의미 아 쉽게 말해서 내가 클릭한 그거 !
            console.log("e.currentTarget:",e.currentTarget) // 리스너를 부착한 객체를 의미 이것도 쉽게 말하면 부모태그요
            console.log("e.target.nodeName:",e.target.nodeName) // 내가 클릭한 그거의 대문자의 태그명!
            if(e.target.nodeName !== 'IMG') return;  // 내가 클릭한게 img태그가 있는 이미지가 맞는지 확인
              //target의 의미는 내가 클릭한 놈!!! 오대박. 이럴 때 쓰는구나...
            big.src = e.target.src;  
        };

        /* 버블링을 막아야 되는 경우  
          요소들이 같은 부모를 공유하지만 다른 이벤트를 처리해야 하는 경우 - 버블링을 막아야 함 !!
          버튼 클릭시 div의 배경색을 변경
          span클릭시 span을 버튼으로, 다시 버튼을 span으로 변경하는 이벤트 처리하는 경우 
          span 클릭 시 부모에게 불필요하게 전달되는것 막아야 함 */
        var fieldset2 =document.querySelector('body > fieldset:nth-child(2)');
        var div = fieldset2.querySelector('.target');
    
        fieldset2.onclick = function(e){
            console.log('fieldset에 클릭이벤트 발생')
            if(e.target.nodeName !=='BUTTON') return;
               //버튼 클릭 시 에만
            div.style.backgroundColor =e.target.textContent // backgrounColor 자바스크립트에스 CSS제어할 때 쓰는 방법...
        };

        var span = fieldset2.querySelector('span');
        var toggle = false;

        span.onclick = function(e){
            e.stopPropagation();// 부모로 가는 이벤트를 막음
            console.log('span에 클릭 이벤트 발생');
            //span을 버튼 요소로 변경
            var button = document.createElement('button');
            button.textContent = span.textContent;
            if( !toggle ){
                button.onclick=e.target.onclick;
                e.target.replaceWith(button);   // span을 버튼으로 변경...
            }
            else{
                e.target.replaceWith(span);  // 버튼을 span으로 변경
            }
             toggle = !toggle;
        };
    });
 
    </script>

1.jpg
0.20MB
2.jpg
0.20MB
3.jpg
0.01MB
4.jpg
0.02MB

EventBubbling15.html
이벤트 버블링을 이용한 이벤트 처리 풍경 첫번째 풍경 두번째 풍경 세번째 풍경 네번째
큰 풍경
이벤트 버블링 막기 즉 부모로 전파되는 이벤트 막기 REPLACE

'학원 > JS' 카테고리의 다른 글

11/08 38-8 [JS] CSSControl  (0) 2022.11.08
11/08 38-7 [JS] EventTrigger  (0) 2022.11.08
11/07 37-3 [JS] EventBasic  (0) 2022.11.07
11/07 37-3 [JS] Date  (0) 2022.11.07
11/07 37-2 [JS] Math  (0) 2022.11.07

Event란 ? 브라우저에서 일어나는 모든 일들을 이벤트라고함 예를들어 마우스로 버튼을 클릭해서 어떤 일들이 벌어진다면 그것은 버튼이벤트라고 함 !

 

 모든 엘리먼트(태그,요소)에는 사용자가 발생시킨 이벤트가 있다.

리스너: 이벤트가 발생할지 듣고 있는 객체
on계열의 리스너가 있다.(onXXXX 여기서 XXXX는 이벤트명 ex. onclick )

리스너는 태그안에 속성으로 기술할 수 있다
     [이벤트 처리방법]
   1.해당 태그에 직접 on계열의 리스너 부착(근데 요렇게는 잘 안씀 유지보수를 위해 분리해 주는게 낫다)
        ex) <a href="#" onclick="이벤트를 처리할 자바스크립트 코드(이벤트 핸들러)">텍스트</a>      
   2. 해당 태그 객체를 얻어 와서 해당 태그 객체의 속성에 익명함수를 할당해서 처리
        ex) <a href="#" >텍스트</a>
        document객체의 getXXXXX()메소드로 얻어 와서
        얻어온 객체.on이벤트명 = function(e){ }    e는 이벤트 객체!
        혹은 얻어온 객체.addEventListener("on을 뺀 이벤트명",function(e){ });  

※load이벤트 부착시에는 addEventListener("load",function(e){ }); 사용하자 (각각의 이벤트를 다 처리해야 하니까 )

 

[주요 이벤트]

DOMContentLoaded 

-  초기 HTML 문서를 완전히 불러오고 분석했을 때 발생.
스타일 시트(.css), 이미지, .JS파일, 하위 프레임의 로딩은 기다리지 않기 때문에 더 빠름

 

load 

- DOM 트리가 생성되고 외부 리소스 파일(이미지나 css혹은  js파일)이 로드 된 경우 발생       
-리스너 : onload

-body태그 안에서만 기술가능         
<body onload="자바스크립트 코드">   요렇게   

 

unload : 이건 사용하지 마세요...  페이지가 닫히거나 다른 페이지로 이동할 때 발생하는 이벤트
        (파이어폭스는 적용 안됨)
-리스너:onunload
 -body태그안에서만 기술가능
 -콜백함수로 처리시에는 window객체에 onload 리스너 부착
 <body onunload="자바스크립트 코드">  암튼 쓰지 마

 submit이벤트 : type="submit" 혹은 type="image"인 경우
클릭 시 발생하는 이벤트 즉, 어떤 값을 action에 지정한 페이지로 전송시(submit) 발생하는 이벤트
-onsubmit
-form태그 안에서 사용가능

reset이벤트 : type="reset"버튼 클릭시 발생하는 이벤트
-onreset
-form태그 안에서 사용가능

click이벤트:  가장 많이 씀. 모든 태그에서 사용가능
 사용자가 해당 엘리먼트(태그)"영역"(컨텐츠 x)을 클릭했을 때 발생하는 이벤트(onclick) 모든 태그에 적용 됨.

change이벤트 : <select> 에서 선택을 바꿀때마다
  아래에서는 onclick을 사용해라
   <input type="radio"
   <input type="checkbox"에서 선택을 바꿀때마다 발생하는 이벤트
        

포커스 관련 이벤트
       focus:포커스(커서)를 얻었을 발생하는 이벤트(리스너:onfocus)
       blur:포커스(커서)를 잃었을때 발생하는 이벤트(리스너:onblur)

 

 *****※이벤트 취소******

리스너에 false를 리턴하면 해당 이벤트가 취소된다     
   예) 유명함수 <태그명 on이벤트명="return false">
         익명함수 태그객체.on이벤트명 =function( ){return false;}

          객체.preventDefault()

 


추가!! 

이벤트 리스너 만드는 법 총 4가지가 있음

1.HTML태그 내에 직접 넣기(이건 권장도 안하고 많이 해서 설명 패쓰)

2.DOM 객체 이벤트 리스너 프로퍼티 리스너 등록

   예시가 이해 쉽지

    var p = document.qureySelector('p');

    function click(){ 함수정의 }

    p.onclick = click;     <- 이땐 함수명만 씀!!

3.DOM 객체 addEventListener( 이벤트 이름  , 리스너로 등록 할 함수 ,  true/false 이건 있을수도 없을수도 )   

    가장 많이 쓰는거 !  안에 여러 함수 중복해서 사용 가능하죠!!

4.익명함수사용 (이거도 종종 많이 사용)

    역시 예시로보면 빠르지

  var p = document.qureySelector('p');

  p.onclick = function(){  함수정의  }

  

하나씩 해봄

1. load

   [방법1]. 태그에 속성으로 on 계열 부착(이게 HTML 태그 내에 직접 부착하는 방법)
       <body onload="alert('body 태그:load이벤트 발생');console.log('body 태그:load이벤트 발생')">

       이건 나중에 유지보수에도 문제가 있기 때문에 잘 사용하지 않음

   [방법2]. 객체의 on계열 속성 혹은  addEventListener("on을 뺀 이벤트명",function(){ })함수로 이벤트  처리

        [2-1] onload 는 맨 나중에  정의한 함수만 최종적으로 호출 됨 !   (이건 익명함수 사용한 방법)

                   window.onload=function( ){            // 이거 발생 안 됨
                           alert('window객체의 onload속성:load이벤트 첫 발생');
                           console.log('window객체의 onload속성 : load이벤트 첫 번째 발생');
                   }
                   window.onload=function(){                // 이거만 됨
                           alert('window객체의 onload속성:load이벤트 두 발생');
                           console.log('window객체의 onload속성 : load이벤트 두 번째 발생');
                   }

      [2-2] addEventListener는 add되기 때문에 순서 상관없이 모든 이벤트 다 호출 됨!

                window.addEventListener('load',function(){               // body  안의 것들의 로드 되고 난 후 발생함
                       console.log('window객체의 addEventListener() : load이벤트 첫 번째발생')
                });

                  window.addEventListener('load',function(){                      // body  안의 것들의 로드 되고 난 후 발생함
                         console.log('window객체의 addEventListener() : load이벤트 두 번째 발생')
                  });

        

** 들어가기 전 ** 폼 땜에 헷깔려서 찾아 봄

form에서 사용되는 각종 양식(input, select, textarea)들을 forms 객체에서 정의할 수 있다고 함

forms 객체는 links, images 등과 같은 "배열" 형태로 document 객체의 하단에 존재하는 객체

그래서 document.forms[ ] 형태로 정의할 수 있다는 것 !

 

예)가 역시 이해가 빠르지 !

 <form action="https://www.naver.com">   → document.forms[0]   첫 번째 폼
<input type="text" name="txt" />  →document.forms[0].elements[0]  첫 번째 폼의 1번째 자식
<input type="submit" value="전송" /> →document.forms[0].elements[1]   첫 번째 폼의 2번째 자식
</form>

<form> →document.forms[1]  두 번째 폼
</form>

 

 

2.DOMContentLoaded

 window.addEventListener('DOMContentLoaded',function(){  // 뒤에 구현할 이벤트들은 여기 안에서 모두 노드시킬 것
              console.log('window객체의 addEventListener(): DOMContentLoaded이벤트 발생')     //이게 젤 먼저 노드 !

               

                이벤트 핸들러(콜백함수)의 이벤트 취소 방법 2가지:    (이벤트 함수랑 콜백함수랑 짝이 맞아야 됨.)      
                 1.return false;  2. 이벤트객체.preventDefault()
                         

                        폼객체.onsubmit = 콜백함수인 경우 
                               -2가지 방법 모두 취소 처리 됨
                         폼객체.addEventListener( )
                               -2번인 이벤트객체.preventDefault()만 적용됨
                         form태그의 onsubmit="return fnSubmit()"일때는 
                                -1번인 return false;만 적용됨 왜냐하면 이벤트객체가 undefined
         
       폼은 이해가 너무 안됨.... 이건 시간 있을 때 다시 천천히 정리하고 다른 거 먼저 정리하자 !!

  console.log(document.forms); //forms자체도 배열의 참조가 될 수 있다!! HTMLCollection { 0:form, length:1 } 유사배열           
            //form 얻어오기
            var form = document.forms[0];
          //  form.onsubmit = fnSubmit;   함수명만 !! () 는 뺀다 
          // 콜백함수를 별도의 외부함수로 정의
          //  form.addEventListener('submit',fnSubmit);      
            
            //콜백함수를 함수 표현식으로 정의
           form.addEventListener('submit',function(e){
            //이벤트 취소하려면 인자인 e (이벤트 객체 필수)
            var text = document.querySelector('[name=txt]');
            if(text.value.trim().length==0){
                alert('입력하세요');
                text.focus();
                if(e !== undefined && e.cancelable){
                  console.log('e.cancelable:',e.cancelable);
                  // 이벤트에 대한 기본동작을 실행하지 않는다               
                  e.preventDefault();   
                } 
            }
           });

 밑에 두 함수는 window.addEventListener('DOMContentLoaded',function(){     요기 안에 다 들어가야 하는것
             3.reset함수 
                      form.onreset = function(){
                                 console.log('reset이벤트 발생');
                                 event.preventDefault();               //reset이벤트발생을 막는 것 (이벤트 취소)
                        };

              4.클릭이벤트 예제
                        var h2 = document.querySelector('#h2');
                        h2.onclick = function(){
                                     console.log('H2영역에 CLICK이벤트 발생:',h2.textContent)
                        };

                    a태그 클릭 시, 클릭이벤트 페이지 이동 막기 (이벤트취소)
                      var aTag =document.querySelector('fieldset a:last-child');
                           aTag.onclick=function(e){
                                         console.log('a태그의 기본 동작:페이지 링크');
                                        if(e.cancelable) e.preventDefault();
                            };
});

 

     // 요게 이벤트 핸들러(콜백함수)
        function fnSubmit(e){
            console.log('이벤트객체:',e);
            var text = document.querySelector('[name=txt]');
            if(text.value.trim().length==0){
                alert('입력하세요');
                text.focus();
                return false; //혹은  그냥 이거로 사용하셈
                /*if(e !== undefined && e.cancelable){ 이벤트의 대한 기본동작을 실행하지 않게 해줌 , 취소가능한지 미리 확인하고 사용하는게 좋음.. (if절)
                  console.log('e.cancelable:',e.cancelable) ;              
                  e.preventDefault();   
                  }*/
            }
        }

 

받은 HTML 문서

<body>
<h2 id="h2">이벤트 기초</h2>
  <fieldset>
      <legend>submit,reset이벤트 및 이벤트 막기</legend>
    <!--
      <form action="https://www.naver.com" onsubmit="return fnSubmit();" >
                                                   return false만 적용됨
    -->
      <form action="https://www.naver.com">
      <input type="text" name="txt" />
      <input type="submit" value="전송" />
      <input type="image"  src="../HTML5/images/button.jpg" alt="image버튼" style="margin-bottom:-6px"/>
      <input type="reset" value="취소" />
    </form>
  </fieldset>
 </body>

 

Click 이벤트 처리 코드

<script>
    function fnClick(obj){
        console.log(obj);
        /*
        onclick 에서 this 는 자기자신의 태크  이벤트핸들러 안에서 this는 이벤트가 가르키는 자기 자신을 가르킨다.
        javascript: 에서 this는 window 객체다
        */
     if(obj.href !== undefined) console.log(obj.href)
    }
</script>

     태그의 onclick 속성으로 이벤트 처리

<fieldset>
    <legend>click이벤트</legend>
    <div style="border:1px red solid" onclick="alert('DIV영역에 클릭이벤트 발생');" >DIV클릭 이벤트</div> 
    <a href="#" onclick="alert('a태그영역에 click이벤트 발생1'); fnClick(this);"  style="background-color: red" >A클릭 이벤트(#)</a>
    <a href="javascript:alert('a태그영역에 click이벤트 발생1');fnClick(this);" style="background-color: green" >A클릭  이벤트(javascript:함수())</a>
    <a href="https://www.nate.com">순수 a태그만</a>
  </fieldset>

 

 

    select

<script>
    function fnSelect(obj){
        console.log('선택된 인덱스:',obj.selectedIndex);
        console.log(obj.options)  // 이거도 유사배열
        console.log('총 아이템 수:', obj.options.length);
        console.log('총 아이템 수:', obj.length);
        
        //선택한 값 얻기
        console.log(obj.value);
        console.log(obj.options[obj.selectedIndex].value);

        //다중선택모드일 때
        for(var i=0; i<obj.length ; i++){
            if(obj.options[i].selected)
            console.log(obj.options[i].value);
        }
        //텍스트 얻기
    console.log(obj.options[obj.selectedIndex].text);
    console.log(obj.options[obj.selectedIndex].textContent);
    console.log(obj.options[obj.selectedIndex].innerHTML);
    console.log(obj.options[obj.selectedIndex].innerText);
    }

    var fnChoice = function(obj){
       console.log(obj.type);
        if(obj.type ==='radio')
            console.log(obj.value,'선택');
        else
            if(obj.checked) console.log(obj.value,'선택');
            else console.log(obj.value,'해제');
    }

    function isSelect(){
        var select = document.querySelector('select');
        if(select.selectedIndex===0){
            alert('학력을 선택하세요');
            select.focus();
        }
        else{
            alert(select.options[obj.selectedIndex].text)
        }
    };

  </script>
  <h2 onclick="isSelect();">선택여부 알아내기</h2>

  <fieldset>
    <legend>change이벤트</legend>
    <select multiple onchange="console.log('change이벤트 발생');fnSelect(this);"> <!--여기 this는 selct 의미함-->
        <option value="">학력 선택</option>
        <option value="초딩">초등학교</option>
        <option value="중딩">중학교</option>
        <option value="고딩">고등학교</option>
        <option value="대딩">대학교</option>
    </select>
    <input type="radio" name="gender" value="남자" onchange="console.log('change이벤트 발생');" onclick="console.log('click이벤트 발생');fnChoice(this)"/>남자
    <input type="radio" name="gender" value="여자"   onchange="console.log('change이벤트 발생');" onclick="console.log('click이벤트 발생');fnChoice(this)"/>여자
    <input type="checkbox" name="inter" value="정치"  onchange="console.log('change이벤트 발생');" onclick="console.log('click이벤트 발생');fnChoice(this)"/>정치
    <input type="checkbox" name="inter" value="경제"   onchange="console.log('change이벤트 발생');" onclick="console.log('click이벤트 발생');fnChoice(this)"/>경제
    <input type="checkbox" name="inter" value="스포츠"  onchange="console.log('change이벤트 발생');" onclick="console.log('click이벤트 발생');fnChoice(this)"/>스포츠
</fieldset>

 

이건 진짜 계속 보고 수정하고 해야겟다... 도저히 무슨말인지 모르겟음....

'학원 > JS' 카테고리의 다른 글

11/08 38-7 [JS] EventTrigger  (0) 2022.11.08
11/07 37-3 [JS] EventBubbling  (0) 2022.11.07
11/07 37-3 [JS] Date  (0) 2022.11.07
11/07 37-2 [JS] Math  (0) 2022.11.07
11/07 37-1 [JS] String  (0) 2022.11.07

Date

Date객체는 var 변수명 =new Date();로 생성한다.     

 

**배열객체 var 배열명 = new Array( );

 

**Math객체 Math.함수명( );

 

**String객체는
방법1) var 변수명 = new String("문자열");
방법2) var 변수명 = "문자열";
혹은 직접 "문자열".함수()형식으로 사용가능
        
날짜 정보를 가져올때는 getXXX()시리즈로
날짜를 설정할때는 setXXX()시리즈로

 

1.Date 객체 얻는 방법 1 : Date( )

 var today = new Date();
console.log('%O, 타입:%s',today,typeof today);
console.log(today);
console.log('년도:',today.getYear()+1900);
console.log('년도:',today.getFullYear());  //자스에 있는 거!! 이러면 년도 바로 출력 가능

 

1-2 Date객체 얻는 방법2:new Date(년[,월,일 ,시,분,초,1000분의 1초])

     월은 0부터 11사이의 값

     년은 그대로 연도를 넣어준다.

 var date2= new Date(2002,5,22,18,10,50);
console.log('%s년 %s월 %s일 %s시 %s분 %s초',
                    date2.getFullYear(),
                    date2.getMonth()+1,
                    date2.getDate(),
                    date2.getHours(),
                    date2.getMinutes(),
                    date2.getSeconds()      
            );   // 2002년 6월 22일 18시 10분 50초

 

2. setXXX()함수로 날짜 변경

date2.setMonth(6);
date2.setDate(31);
console.log('%s년 %s월 %s일 %s시 %s분 %s초',
                    date2.getFullYear(),
                    date2.getMonth()+1,
                    date2.getDate(),
                    date2.getHours(),
                    date2.getMinutes(),
                    date2.getSeconds()      
             );  //2002년 7월 31일 18시 10분 50초

 

3. 요일 얻기:getDay() 0:일요일 1:월요일,2:화요일...

  switch(date2.getDay()){
      case 0 : console.log('일요일'); break;
      case 1 : console.log('월요일'); break;
      case 2 : console.log('화요일'); break;
      case 3 : console.log('수요일'); break;
      case 4 : console.log('목요일'); break;
      case 5 : console.log('금요일'); break;
      case 6 : console.log('토요일'); break;
    };  // 수요일

 

4.두 날짜 사이의 차이 구하기(getTime () )

   1970년 1월 1일 0시 0분 0초부터 특정일까지 흘러온 시간을 1000분의 1초(miliseconds)단위로 반환.

var currDate = new Date();    //오늘날짜(시작날짜)
var endDate = new Date('2023-2-23');  // 끝 날짜
var cTime = currDate.getTime();  // 시작날짜를 1970 기준으로 단위 반환
console.log(cTime);
var eTime = endDate.getTime();   // 끝 날짜도 단위 반환
console.log('수료일까지 남은 일 수:',Math.ceil(Math.abs(cTime-eTime)/(1000*60*60*24)));

 

 

5.Date.now() : 1970년 1월 1일 00:00:00 UTC로부터 지난 시간을 밀리 초 단위의 숫자 값으로 반환

   console.log('Date.now():',Date.now())   // cTime과 똑같다...

 

 

6.date.parse() : 날짜를 나타내는 "문자열"을 "날짜"로 변환 후 해당날짜랑 1970년 1월 1일 00:00:00 UTC의 시간 차이를 밀리 초 단위의 숫자 값으로 반환

var parseTime = Date.parse('2022-09-14');    //날짜를 나타내지만 문자열임 

console.log('parseTime:',parseTime);  // 날짜로 변환했지만 ..1663113600000  값이 어마어마하다...

아무래도 저렇게 출력되면 보기 힘드니 보기 편하게 연, 월, 일로 변환

   1. Date 객체 생성(오늘날짜로)
        var temp = new Date();
   2. setTime() 함수로 오늘날짜에서 구하려는 날짜변경

        temp.setTime(parseTime);   // temp는 현재 날짜에서 parse날짜로 설정

console.log('%s년 %s월 %s일 %s시 %s분 %s초',
                    temp.getFullYear(),
                    temp.getMonth()+1,
                    temp.getDate(),
                    temp.getHours(),
                    temp.getMinutes(),
                    temp.getSeconds()      
        );   //  2022년 9월 14일 9시 0분 0초

'학원 > JS' 카테고리의 다른 글

11/07 37-3 [JS] EventBubbling  (0) 2022.11.07
11/07 37-3 [JS] EventBasic  (0) 2022.11.07
11/07 37-2 [JS] Math  (0) 2022.11.07
11/07 37-1 [JS] String  (0) 2022.11.07
11/4 36-11 [JS] BOM_2  (0) 2022.11.05

Math

 클래스 메소드임으로 Math.함수명() 식으로 호출한다.

한 번씩 출력해보고

console.log(Math)   //Math { }
console.log(Math.PI)   //3.141592653589793

 

1. abs()절대값
   console.log('-10의 절대값:',Math.abs(-10));   //-10의 절대값: 10
2. .pow():지수
    console.log('2의 3승:',Math.pow(2,3));  //2의 3승: 8
3. round():반올림
     console.log('반올림:',Math.round(3.159));  //반올림: 3
4. ceil():올림 
     console.log('올림:',Math.ceil(3.159));   //올림: 4
5. floor():내림
     console.log('내림:',Math.floor(3.159));  //내림: 3

 

6. random
    parseInt(Math.random()*범위) + 시작값
    ex)
    1부터 5사이의 숫자를 랜덤하게 발생시키자
    범위:5-1 = 4
    시작값:1
    parseInt(Math.random()*4)+1:마지막값 5는 포함 안됨

    ※마지막 값을 포함 : 범위 + 1
    parseInt(Math.random()*5)+1:마지막값 5도 포함됨
    

 console.log(Math.random());
 console.log(parseInt(Math.random()*5)+1);   //1~5까지 랜덤하게 나옴

 

 문제)
    1부터 45까지 숫자를 랜덤하게 6개 발생시키자. 단, 숫자는 중복되면 안됨.(즉 로또번호 생성)

 <fieldset>
        <legend>로또 발생기</legend>
        <button onclick="showLottoNumber();">로또 발생</button>
        <span id='lotto' style='font-size:2em;color:red;font-weight:bold;'></span>
  </fieldset>
  <sctopt>
   
      //1.함수정의:자바코드를 자스코드로 변환
      //랜덤하게 숫자 발생후 중복되지 않게 배열에 저장하는 메소드]
       function setRandomNumb (random,start,end){
        for(var i=0 ;i< random.length;i++) {
            while(true) {
                var randomNumber=parseInt(Math.random()*(end-start+1))+start;
                var  isDuplicated = false ;
                for(var k=0 ; k <= i-1 ; k++) {
				    if(randomNumber == random[k]) {  //중복일때
					isDuplicated = true;
					break;
				    }	
                }
                    if(!isDuplicated) { //중복아닐때
				       random[i]=randomNumber;		
				       break;
			        }			   		
            }
        }
    }
  
  
      //2.함수 호출       
      var lotto = new Array(6);
      setRandomNumb(lotto,1,45);
      
      //3.span에 출력      
      var span = document.querySelector('#lotto');
      function showLottoNumber(){
        lotto = new Array(6);
        setRandomNumb(lotto,1,45);
        var lottoNumber = '';
        lotto.forEach(function(item){
            lottoNumber+=item+'  ';
        });
        span.textContent=lottoNumber;
      }
</script>
로또 발생기

 

'학원 > JS' 카테고리의 다른 글

11/07 37-3 [JS] EventBasic  (0) 2022.11.07
11/07 37-3 [JS] Date  (0) 2022.11.07
11/07 37-1 [JS] String  (0) 2022.11.07
11/4 36-11 [JS] BOM_2  (0) 2022.11.05
11/4 36-10 [JS] BOM_1 (각종 함수들)  (1) 2022.11.05

+ Recent posts