이건 좀 많이 필요 할 거 같아서..

 

제이쿼리로 유효성 검사하려면

따로 플러그인 가져와야 함 

https://jqueryvalidation.org/ 요기서 참고

제이쿼리 유효성 검증 용 플러그인
  <script src="../js/jquery.validate.min.js"></script>

요렇게 다운받놓고 쓰거나 cdn로 쓰거나


 <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>

 

우선 폼 

 

** 참고


 체크박스나 라디오버튼은 에러 메시지가
첫번째 체크박스 나 첫번째 라디오버튼 다음에 표시됨.
 label태그를 이용해서 특정 위치(단,form태그안에서만)에 에러메시지를 뿌려 줄 수 있다.

<fieldset>
  <legend>제이쿼리의 플러그인을 사용한 유효성체크</legend>
  <span style="color: red; font-size: 1.8em"></span>
  <form method="post" action="http://www.nate.com" id="frm">

    이름:<input type="text" name="name" /><br /> 
    <label for="id">아이디:</label>
    <input type="text" value="" name="id" id="id" /><br /> 
    비밀번호:<input
      type="password" name="pwd" id="pwd" /><br /> 비밀번호 확인:<input
      type="password" name="pwd2" /><br />
      이메일 : <input type="email" name="email"/><br/>
     
      관심분야: <input type="checkbox"
      name="inter" value="A" id="pol" />정치 
      <input type="checkbox"
      name="inter" value="B" />경제 
      <input type="checkbox" name="inter"
      value="C" />스포츠
      
     <!--
     for속성:name 속성에 지정한 값
     class속성:반드시  "error" 문자열
                           -->

      <label for="inter" class="error"></label><br /> 성별: 남자<input
      type="radio" name="gender" value="man" /> 여자<input type="radio"
      name="gender" value="woman" /> <label for="gender" class="error"></label><br />

    <!-- 
          option태그의 value속성에 빈 문자열("")을
          설정하면 선택 하지 않은 것으로 간주한다.

         -->
    <select name="sel">
      <option value="">==학력을 선택하세요==</option>
      <option value="uni">대학교</option>
      <option value="high">고등학교</option>
      <option value="middle">중학교</option>
      <option value="ele">초등학교</option>
    </select><br /> <input type="file" name="file" /><br /> 자기소개<br />
    <textarea name="self" cols="50" rows="5"></textarea>
    <br /> 
    <input type="button" value="button타입" /> 
    <input type="submit" value="submit타입" /> 
    <input type="reset" value="취소" />

  </form>
</fieldset>

 

**   ※$(폼 선택자).validate({rules:{},messages:{}});
      rules규칙:
        -필수 입력 혹은 필수 선택(체크박스/라디오/선택상자)
        하위요소명 : "required"
        혹은
        2개 이상  규칙 적용시
        required:true 
        -최소 몇자 이상 혹은 몇개 이상 선택
        minlength:최소수

  $(function(){
       //1]input type="submit"버튼 일때
       $('#frm').validate({
        rules:{//유효성 규칙 설정
          name:"required",
          id:{required:true,minlength:4,maxlength:8},
          pwd:{required:true,minlength:5},
          pwd2:{required:true,minlength:5,equalTo:'#pwd'},
          email:{required:true,email:true},
          inter:{required:true,minlength:2},
          sel:"required",
          gender:"required",
          file:"required",
          self:"required"
       },
       messages:{
        name:"이름을 입력하세요",
        id:{required:"아이디를 입력하세요",minlength:'아이디는 최소 4자이상입니다',maxlength:'아이디는 최대 8자까지 입니다'},
        pwd:{required:"비밀번호를 입력하세요",minlength:"비밀번호는 최소 5자이상입니다"},
        pwd2:{required:"비밀번호확인을 입력하세요",minlength:"비밀번호확인는 최소 5자이상입니다",equalTo:'비밀번호가 일치해야 합니다'},
        email:{required:"이메일을 입력하세요",email:"이메일 형식이 아닙니다"},
        inter:{required:'관심분야를 선택하세요',minlength:'관심분야는 최소 2개이상 선택하세요'},
        sel:"학력을 선택하세요",
        gender:"성별을 선택하세요",
        file:"파일을 첨부하세요",
        self:"자기소개를 입력하세요"
      }});

       2]input type="submit"버튼이 아닐때
          1. $(폼객체 선택자).validate()적용
		  2. $(폼객체 선택자).valid()호출 
	         true반환 시 $(폼객체 선택자).submit()호출한다
      $(':button').click(function(){
          if($('#frm').valid()){
            $('#frm').submit();
          }
      });
    });

오오 개인프로젝트에 사용해야지 개꿀!

 

[ReplaceWith]

얘도 말그대로 대체하는 거겠지..

<fieldset>
    <legend>replaceWith()함수</legend>
    <div>div1</div>
    <div>div2</div>
    <div>div3</div>
    <button>확인</button>
</fieldset>

버튼이였다가 그냥 div였다가 

 $(function(){
    $(':button').click(function(){
        if($('div').length === 0){
            $('button').not(':last').each(function(){
               $(this).replaceWith('<div>'+$(this).html()+'</div>');
            })
        }
        else{
            $('div').each(function(){
               $(this).replaceWith('<button>'+$(this).html()+'</button>');
            })
        }
    });
});

 


[Each Trim]

제이쿼리 함수 : 자스의 forEach나 for~in문 역할
$.each(배열이나 객체,function(키값,밸류값){});
만약 배열 형태라면
첫 인자에는 인덱스 ,두 번째 인자에는 인덱스에따른 요소값이 저장 됨.
배열이나 객체에 적용할 때
$.each(배열,function(인덱스,인덱스에따른 요소값){ });

 

 

특정 요소들 즉 선택한 태그들에 적용할때 $(선택자).each(function(인덱스,요소){ })

 

<fieldset>
    <legend>$.each(대상,콜백함수) 및 $.trim(문자열)</legend>
</fieldset>

 

var mountains=['한라산','지리산','덕유산'];
        $.each(mountains,function(index,element){
            console.log(index,element);
        });

        var member ={name:'가길동',age:20,addr:'가산동'};
        console.log(member.name,member['name']);
        $.each(member,function(key,value){
            console.log(key,value);
       //     console.log(member.key)  // undefined key라는 키는 없음
       console.log('member[key]',member[key])   //키가 변수 일 때는 []로 감싸자 !!!*************
        });

        var members=[
            {name:'가길동',age:20,addr:'가산동'},
            {name:'나길동',age:30,addr:'가산동'},
            {name:'다길동',age:25,addr:'다산동'}
    ]
    $.each(members,function(index,element){
            console.log('번호:%s,이름:%s,나이:%s,주소:%s',index+1,element.name,element.age,element.addr);
        });
    console.log('X'+('     j Q U    ER            Y       ')+'Y');
    console.log('X'+$.trim('     j Q U    ER            Y       ')+'Y');

 

이렇게 하고

 JQUERY UI 사용법을 배웠는데

필요한 건 홈페이지가서 찾아서 쓰면 될 듯? 굳이 정리 안하겠음... 절대 귀찮아서 그러는 것 아님다만 주의할 것은 라이브러리 잘 가져오는것!!코드해석을 잘 해서 가져오자 !이제 개인과제해야지

ui쓸때 필요

[Append계열]

DOM객체를 동적으로 추가시키는 함수들워.... 어지러움 폼

<fieldset>
    <legend>DOM객체를 동적으로 추가하는 함수들</legend>
    <h2>
        <span>제목입니다</span>
    </h2>
    <input type="text" id="row" />행 <input type="text" id="col" />열
    <input type="button" value="테이블 동적 생성" />
    <table style="border-spacing: 1px; background-color: red">
        <tr style="background-color: white">
            <td>1행 1열</td>
            <td>1행 2열</td>
        </tr>
        <tr style="background-color: white">
            <td>2행 1열</td>
            <td>2행 2열</td>
        </tr>
    </table>	

    <div id="lblDisplay" style="border: 1px red solid; width: 600px">
        대상<br />대상2
    </div>	
</fieldset>

이건 직접  하나씩 해봐야지 알 수 있어서 코드만 우선 적어놓고..

$(function(){
        $(':button').click(function(){
            var table="<table style=\"border-spacing: 1px; background-color: red\">";
            var row=$('#row').val();
            var col=$('#col').val();
            for(var i=1; i<=row;i++){
                table+="<tr style='background-color:white'>";
                    for(var k=1 ;k<=col;k++){
                    table+="<td>"+i+"행"+k+"열</td>";
                    }
                    table+="</tr>";
            }
            table+="</table>"  ;
            
            append계열 함수 미사용
            $('#lblDisplay').html($('#lblDisplay')+table);  //대상 뒤로
            $('#lblDisplay').html(table+$('#lblDisplay'));  //대상 앞으로
            
            추가할 대상의 컨텐츠 이후에 추가됨
            $('선택자').append('추가 할 요소')
            $('선택자').append($()함수를 기존 객체 선택)
            $('#lblDisplay').append(table);
            $('#lblDisplay').append($('table:first')); //기존요소 appand 하면 잘라내서 붙여넣기함

            $('추가 할 요소').appendTo('선택자')
            $(table).appendTo('#lblDisplay'); //appand랑 똑같음
            $('table:first').appendTo('#lblDisplay');
            
                befor() : -DOM요소 이전에 html요소 추가
                			$('선택자').before('html요소');      
                after() : -DOM요소 다음에 html요소 추가
                			$('선택자').after('html요소');

                insertAfter():위랑 같은데 인자순서만 달라짐
               			 $('html요소').insertBefore('선택자');		
                insertBefor():얘도
               			 $('html요소').insertBefore('선택자');
            
          $('#lblDisplay').before(table);
          $('#lblDisplay').before($('table:first')); // 잘라내서 붙여넣기함
          $('#lblDisplay').after(table);
          $('#lblDisplay').after($('table:first')); 
        });
    });

[Clone]

말그대로 복제하는 함수

여기서 핵심은

원본을 그대로 유지하느냐 마느냐!!!

 

<fieldset>
    <legend>clone()</legend>

    <div class="clone">원본</div>
    <div class="clone" >대상</div>

    <hr/>
    <button>문제 추가</button>
    <hr />
    <div>
        <span>문제1번</span>
        <input type="text" name="problem1" style="width: 60%" />
    </div>

</fieldset>

이거 팀프로젝트에도 적용 할 수 있을 것 같은데은근히 동적으로 뭘 추가해야 할 게 많다..문제는 추가는 하는데 그걸 저장하는게...아무튼 이렇게 하는거 익혀두자 !!!

$(function(){
       $('.clone').eq(0).click(function(){
        원본을  잘라내서 붙여넣기 효과
        var origin=$(this).css('backgroundColor','yellow').html('복제');
        $('.clone:eq(1)').after(origin);
        
        원본 복제(clone함수)후 복제본을 변경 한 후 after()함수 적용: 원본은 그대로 유지 됨
        var clone=$(this).clone().css('backgroundColor','yellow').html('복제');
        $('.clone:eq(1)').after(clone);
       });

       설문지 문항 동적으로 추가하기
       var index=1;
       var problem= $('div:last');
       $(':button').click(function(){
             클론함수 미사용
            $('div:last').after("<div><span>문제"+ ++index+"번</span><input type=\"text\" name=\"problem"+index+"\" style=\"width: 60%\" /></div>");
             클론함수 사용
            $('div:last').after(problem.clone().find('span').html('문제'+ ++index+'번').next().prop('name','problem'+index).parent());
        });
    });

[Wrap]

태그로 감싸기

 

 

<fieldset>
    <legend><span>wrap()함수</span></legend>
    <h2><span>포탈 사이트</span></h2>
    <ul>		 
      <a href="http://www.naver.com/">네이버</a>
      <a href="http://www.daum.net/">다음</a>
      <a href="http://www.nate.com/">네이트</a>
    </ul>
      <hr/>
      <button>span태그 감싸기</button>
      <button>a태그 감싸기</button>	     
</fieldset>
<script>
    $(function(){
        $('button').eq(0).on('click',function(){
            $('span:first').wrap('<strike>').wrap('<strong>');
        });
        $('button:last').click(function(){
            $('a').wrap('<li>');
        })
    });
</script>

바뀜!


[RemoveEmpty]

  $("선택자") 하면 해당 객체가 없어도 무조건 jQuery객체 반환.
 null이나 undefined가 아님
 따라서 해당 객체 존재 유무는 null이 아닌
 $("선택자").length==0으로 판단해야 한다!!

 

<fieldset>
    <legend>remove()및 empty()함수</legend>
    <button>REMOVE</button>
    <button>EMPTY</button>
    <div style="color:green;border:1px red solid">DIV</div>
</fieldset>

 

$(function(){
    console.log($('h2')===null ? 'H2요소가 없다' :'H2요소가 있다' );   //H2요소가 있다  에라이
    console.log($('h2')===undefined ? 'H2요소가 없다' :'H2요소가 있다' );  //H2요소가 있다 에에에라이
    console.log($('h2').length ===0 ? 'H2요소가 없다' :'H2요소가 있다' );  //H2요소가 없다 그러취!

    $(':button').click(function(){
        console.log($(this).is(':first'));  //false
        console.log($(this).is('button:first'));// 꼭 button 적어줘야 나온다 ! 아하!
       if($(this).is('button:first')){
        //요소가 완전히 삭제됨
        $('div').remove()
       }
       else{
        //div 요소는 존재 내용만 지운다
        $('div').empty()
       }
    });
  });

 

 

 

[EQ]

.eq()

선택 된 객체 중에서 기술된 순서대로
인덱스가 부여됨(인덱스 0부터 시작!) 즉 부모  자식관계와는 무관

 

<fieldset>
    <legend>eq()함수</legend>
    <h2>당신이 좋아하는 과목은?</h2>
    <ul>
        <li>자바</li>
        <li>닷넷</li>
        <li>스프링</li>
        <li>제이쿼리</li>
    </ul>
    <h2>당신이 좋아하는 산은?</h2>
    <ul class="mountain">
        <li>지리산</li>
        <li>설악산</li>
        <li>소백산</li>
        <li>한라산</li>
    </ul>
    <button>확인</button>
</fieldset>

저렇게 인덱스 변수처리할 때 좋군

 $(function(){
    $('button').click(function(){
        console.log('선택기 필터 사용:',$('li:eq(4)').html()); //li중에서 인덱스4인 요소
        console.log('eq()함수 사용:',$('li').eq(4).html());   
        //인덱스변수처리할 때는 eq()함수가 유리
        var index=6;
        console.log('선택기 필터 사용:',$('li:eq('+index+')').html());
        console.log('eq()함수 사용:',$('li').eq(index).html());
    })
});


[IS]

이도끼가 네도끼냐 ?

처럼 조건걸러네는 함수

 

<fieldset>
    <legend >boolean is(선택자)</legend>
    <input type="checkbox" />동의
    <p id="mydiv">
        <input type="text"/>
        <input type="text"/>			
        <input type="button" value="버튼"/>
        <input type="file"/>			
    </p>
</fieldset>

 

나 :이거 너무 헷깔려서 찍어봄

console.log($(':checkbox'))  //0: <input type="checkbox">
 console.log($('checkbox'))  //Object { 0: HTMLDocument http://127.0.0.1:5500/core/IS.html}

:요거가 있으면 걍 그 요소를 가져오나봄 

아하!

$(function(){
        $('legend').click(function(){
            console.log($(':checkbox').is(':checked')); //체크박스가 체크되었느냐?
            console.log($('#mydiv').is('div'))  //false               
        })
        
        
        $('#mydiv').children().each(function(index,element){

           문]두번째 텍스트박스를  위쪽 및 좌우 테두리는 제거하고 아래쪽 
             테두리만 1px green solid로 설정하여라,
             단 is()함수를 사용하여라.                  
      
         	$('input[type=text]').eq(1).css({border:'none',borderBottom:'1px green solid '})
        	이렇게 하고 좋아했는데 is 함수를 써야 했네 .. 하 놔...
        
       	 	console.log('인덱스:%s,찾는요소:%s',index,$(this).is(':text:eq(1)'));
         	if($(this).is(':text:eq(1)')){
            	$(this).css({border:'none',borderBottom:'1px green solid '});
           }
        });
    });

요렇게 적용 됨


[Not]

이름하야 걔 빼고 함수

 $(선택자).not(제거할 선택자) : 선택한 객체 중에서 제외하고 싶은 선택자 지정

 

<fieldset>
    <legend>not("선택자")함수</legend>
    <a href="www.naver.com">네이버</a>
    <a href="www.daum.net">다음</a>
    <a href="Form3.jsp">페이지로1</a>
    <a href="Form4.jsp">페이지로2</a>
    <a href="www.cyworld.com">싸이월드</a>
    <a href="Form5.jsp">페이지로3</a>		 
    <button id="btn">확인</button>
</fieldset>

not함수 미사용 시 filter()를 이용해도 됨 하지만 간편한게 있으면 간편한걸 써야지

$(function(){     
       var href=""; 
      
      not함수 미 사용
      $('#btn').click(function(){         
          $('a').filter('[href^=www]').each(function(){ //www로 시작하는 요소들
              href+=$(this).attr('href')+' ';
            });
          console.log(href);   //www.naver.com www.daum.net www.cyworld.com
       });    
        
        not함수 사용
        $('#btn').click(function(){  // jsp포함된거 빼고
        $('a').not('[href$=jsp]').each(function(){
                href+=$(this).attr('href')+' ';
            });
       	 console.log(href); //www.naver.com www.daum.net www.cyworld.com 
        });
       
    });

 


[EndFind]]

 

end(): 바로 이전 선택된 객체를 반환(즉 end()함수가 적용된 바로 이전 객체)
$('선택자'),find('찾을 선택자'):find는 선택된 객체의 하위(손자,자식 다 포함)에서 찾음   

 

<fieldset>
    <legend>end()함수/find(선택자)함수</legend>
    <span title="SPAN1">SPAN1</span>
    <span title="SPAN2">SPAN2</span>
    <span title="SPAN3">SPAN3</span>
    <div>
        <p>
            <b>축구</b>
        </p>
        <p>
            <b>농구</b>
        </p>
        <p>
            <b>배구</b>
        </p>
        <button>확인</button>
    </div>
</fieldset>

헷깔릴 수도 있겠당....

$(function(){
    $('button').click(function(){
      console.log($('div').find('p:last').find('b').html());
      console.log($('div').find('p:last').text());
      console.log($('div p:last').text());
      console.log($('div').find('p:last').find('b').end().html());
      console.log($('div').end().length);    //요소를 못 찾아도 1 반환
        try{
            console.log($('div').end().html());   // 에러나서 try~catch로 잡음
        }
        catch(e){
            console.log('요소를 못 찾았어요',e.message)
        }

   $('span').css('color','red').eq(0).css('border','1px  red solid').end().eq(2).css('border','5px green solid');
    })

});

콘솔창확인
css적용

 

 

[FormSelector]

말도많고 탈도많은 form...

폼을우선...

<fieldset>
    <legend>jQuery의 폼 셀렉터</legend>
    <input type="button" value="Input Button"/><br />
    <input type="text"/><br />

    <input type="password"/><br />
    <input type="checkbox" value="정치" name="inter"  />정치
    <input type="checkbox" value="경제" name="inter"/>경제
   <input type="checkbox" value="연예" name="inter"/>연예
    <br />
    <input type="file" /><br />
    <input type="hidden" value="히든값"/><br />
    <input type="image" alt="이미지"  src="../images/1.jpg"/><br />
    <input type="radio" value="남" name="gender" />남
    <input type="radio" value="녀" name="gender"/>녀
    <br />
    <input type="reset" value="취소"/><br />
    <input type="submit" value="전송"/><br />	
    <select multiple >
        <option value="" >학교를 선택하세요</option>
        <option value="초등학교">초등학교</option>
        <option value="대학교">대학교</option>
    </select><br />

    <textarea >텍스트 에리어</textarea><br />
    <button>값 읽기</button>
    <button>값 설정</button>	    
</fieldset>

익숙한 폼이다... 으

1]input 과 :input 선택자
$("input") - input으로 시작하는 모든 태그 선택
$(":input") - input태그뿐만 아니라 폼의 모든 하위요소 태그 선택
폼 엘리먼트만 선택 ( input, select, textarea, button )

console.log('input태그 선택자:',$('input').length); //13
console.log(':input 폼 선택자:',$(':input').length); //17
console.log(':button 폼 선택자:',$(':button').length); // <button>도 포함됨 3개

val()함수- 폼의 하위요소의 값을 읽어오거나 설정]
-읽어올때 :$("폼 하위요소").val();
-설정할때 :$("폼 하위요소").val("값")


[값 읽기]
1.input type ="button"혹은 <button>태그
$(":button")으로 선택 시 input type="button"뿐만 아니라 <button>태그도 선택됨.
input type="button"만 선택하고자 할때는
$("input[type=button]") 혹은
$(":button[type=button]")

$(':button').each(function(index){   //  :button 하면 총 3개나옴
      console.log('%s버튼의 type속성:%s',index,$(this).prop('type'));
      console.log('%s버튼의 value속성:%s',index,$(this).prop('value'));
        if($(this).is('[type=button]')){  //
            console.log('버튼의 텍스트:',$(this).val());
        }
        else{ /// button태그 (type=submit)
            console.log('버튼의 텍스트:',$(this).html());
        }
});

2.input type="text"
:text 나 혹은 input[type=text]

console.log('type=text의 개수 :',$(':text').length);
console.log('type=text의 값 :',$(':text').val());

3.input type="password"
:text 나 혹은 input[type=password]

console.log('type=password 개수 :',$(':password').length);
console.log('type=password 값 :',$(':password').val());


4. :checkbox 혹은 input[type=checkbox]
$(":checkbox").val() : 체크 된 값을 읽어오는게 아니라 첫 번째 체크박스의 value값을 읽어 온다.
※체크된 것만 읽고자 할때
$(":checkbox:checked")에 each( )함수를 적용해서 얻는다.
$(":checked")는 체크박스.라디오버튼.선택상자 모두 포함해서 체크 된 모든 객체를 의미

console.log('체크된 총 요소 수:',$(':checked').length);
체크 상관없이 무조건 첫 번째 값만 읽어욤
console.log($(':checked').val()) 

체크된 것만 읽어오기
console.log('1. :checkbox:checked 와 each()함수 사용');
  $(':checkbox:checked').each(function(){
  console.log($(this).val())
  })

console.log('2. :checkbox 와 filter함수 each()함수 사용')
    $(':checkbox').filter(':checked').each(function(){
    console.log($(this).val())
})
console.log('3. :checkbox 와 if함수 each()함수 사용')
    $(':checkbox').each(function(){
        if($(this).prop('checked'))
            console.log($(this).val());
})


5.input type="file"

 console.log('type="file:',$(':file').val());


6.input type ='hidden'선택하지말고input[type=hidden]

console.log(':hidden:',$(':hidden').length); //12개 어휴 너무많아
$(':hidden').each(function(index,item){
	console.log('인덱스:%s,요소:%s',index,item)
	})
console.log('input[type=hidden]:',$('input[type=hidden]').length);
console.log(':input:hidden:',$(':input:hidden').length);


7.input type='image' :valu가없어서 값을 얻어올 수 없다
console.log('type=imaage:',$(':image').prop('src'))

8.input type='radio'
console.log('성별:%s',$(':radio:checked').val())

9.select태그:select 없다
console.log($(':select').val()) ==> error 이런 건 없음!!
console.log('select:',$('select').val())

다중선택 시
console.log(':selected:',$(':selected').val()) =>이건 O
$('select').children(':selected').each(function(){
console.log($(this).val())
})

10. textarea태그 얘도 :textarea는 없음
console.log("textarea(val):",$('textarea').val());
동적으로 변한 값은 읽어오지 못한다.
console.log("textarea(val):",$('textarea').html());


[값 설정] : 그나마 간단하니 한큐로

 폼의 하위요소 값 설정
1.input type="button"
$(':button:first').val('입력버튼');

2.input type="text"
$(':text').val('아이디를 입력하세요');  // 추가는 되지만 렌더링은 안됨 소스보기에선 안바뀜

3.intputype='password'
$(':password').val('1234');

4.체크박스 !!!
우왕신기  반드시 배열 초기화자[]로 값 설정 
방법1] 반드시 배열 초기화자[]로 값 설정	  
	 var checkBox =[];
	 checkBox.push('정치');
	 checkBox.push('연예');
	 $(':checkbox').val(checkBox);
     $(':checkbox').val(['정치','연예']);
 방법2] prop()함수 로 checked 속성 이용
   $(':checkbox').val(['정치','연예']);
   $(':checkbox[value=정치],:checkbox[value=연예]').prop('checked',true);

5.input type ="radio"  왜 대괄호냠... 값이 하나라도 반드시 [] 사용해
$(':radio').val(['녀']);              

6.select태그
방법1]val()사용
$('select').val(['초등학교','대학교']) 속성이 multiple 일 때
$('select').val('대학교')  
방법2]attr()함수 로 selected 속성 이용
$('select').children('[value=대학교]').prop('selected',true);
7.textarea
$('textarea').val('안녕하세요\r\n반가워요\r\n안녕');

 


FormSelectorExam

폼이요...

<fieldset>
    <legend>폼 셀렉터 연습</legend>
    <h2>텍스트 복사</h2>
    <input type="text"  id="src" />
    <input type="button" value="복사" />
    <input type="text"  id="desc" />
    <h2>선택상자의 값 복사</h2>
    <select  id="sel" >
        <option value="baseball">야구</option>
        <option value="balleyball">배구</option>
        <option value="scocker">축구</option>
    </select>
    <input type="text" id="sport" />
    <h2>radio상자의 값 복사</h2>
    <input type="radio" name="gender" value="M" />남자
    <input type="radio"	name="gender" value="W" />여자
    <input type="text" id="gender" />
    <input type="button" value="확인" id="btn" />
    <h2>메일선택</h2>
    <input type="checkbox" value="all">전체 선택
    <ul style="list-style-type: decimal;">
        <li><input type="checkbox" name="mailing" value="mail1" />메일1</li>
        <li><input type="checkbox" name="mailing" value="mail2" />메일2</li>
        <li><input type="checkbox" name="mailing" value="mail3" />메일3</li>
        <li><input type="checkbox" name="mailing" value="mail4" />메일4</li>
        <li><input type="checkbox" name="mailing" value="mail5" />메일5</li>
        <li><input type="checkbox" name="mailing" value="mail6" />메일6</li>
        <li><input type="checkbox" name="mailing" value="mail7" />메일7</li>
    </ul>
</fieldset>
$(function(){
    $(':button:first').click(function(){
        $('#desc').val($('#src').val());
    })

    $('#sel').change(function(){
        $('#sport').val($(this).val()==='baseball'? '야구' : $(this).val()=="balleyball" ? '배구' : '축구')
    });

    $('#btn').click(function(){
        $('#gender').val($(':radio:checked').val() === 'M'? '남자':'여자');
    })

         

    문제. 메일전체선택/해제 하기
    var mailingLength = $(':checkbox').slice(1).length;
    console.log('mailingLength:',mailingLength)
    $(':checkbox').click(function(){
        if($(this).val()==='all'){
            if($(this).prop('checked')) $(':checkbox').slice(1).prop('checked',true);
            else $(':checkbox').slice(1).prop('checked',false);
        }	
        else{
            if($(this).prop('checked')){
                if(mailingLength===$(':checkbox:checked').length){
                    $(':checkbox:first').prop('checked',true)
                }
                else
                $(':checkbox:first').prop('checked',false)
            }
        }
    });


  });



[Attr]

 

요기능은 잘 쓴다고 하니 잘 익혀두자 !!

 

[속성 읽기]

$("선택자").attr("속성명") 

요렇게 사용

$("선택자").get(인덱스).속성명 

요렇게도 가능한 것

해당 태그에 속성명 미 기술시에는 읽어 오지 못함

그래서 읽을 땐 prop()사용 !

 

[속성 설정]

$("선택자").attr("속성명","속성값")
동시에 여러 속성 설정시에는 메소드 체인을 이용하거나 JSON데이타 형식 사용
 attr({속성1:'속성1값',속성2:속성2값.....})

 

[속성 제거]

$("선택자").removeAttr("속성명"); 

 

****속성 추가 시는 attr()이나 prop()사용
 속성 읽기 시는 prop()사용 ,만약 HTML태그상에 속성이 기술이 안되어 있다면 
      attr()은 undefined
      prop()은 빈 문자열 이기 때문...
속성 삭제 시에는 removeAttr()사용.

(removeProp()은   HTML태그의 속성은 제거가 안된다.)

 

 

폼(추가/읽기/제거)

<fieldset>
    <legend >attr()함수 및 removeAttr(),prop()함수</legend>
    <button id="add">속성추가</button>
    <button id="read">속성읽기</button>
    <button id="remove">속성제거</button>
</fieldset>

 

1.속성 추가

$('#add').click(function(){
    attr()함수사용 (메소드 체인)
 	$('#div').attr('title','여기를 클릭 하세요')
             .attr('class','bg')
             .attr('style','width:100px; height:100px;text-align:center;line-height:100px')
             .on('click',function(){
                $(this).html('JQUERY');
             }); 

    JSON데이터 형식 사용
    $('#div').attr({title:'여기를 클릭하세요','class':'bg','style':'width:100px; height:100px;text-align:center;line-height:100px'})
             .on('click',function(){
                $(this).html('JQUERY');
             });           
});

 

2.속성 읽기

**태그의 class속성은 className으로 접근한다

 $('#read').click(function(){
    console.log('체크박스 checked속성(attr함수):',$(':checkbox').attr('checked'));  // undefined 얘는 값을 그대로 읽어 옴
    console.log('체크박스 checked속성(prop함수):',$(':checkbox').prop('checked'));  //false 상태를 보고 true/false 반환

    console.log('링크태그의 href속성(attr함수):',$('#atag').attr('href'));   // #
    console.log('링크태그의 href속성(prop함수):',$('#atag').prop('href'));   // http://127.0.0.1:5500/core/Attr.html#

    console.log('div태그의 class속성(attr함수):',$('#div').attr('class'));   // undefined    bg
    console.log('링크태그의 class속성(prop함수):',$('#div').prop('class'));   // <empty string>  bg

	**태그의 class속성은 className으로 접근한다 (왜? class 자바스크립트의 키워드임 !)
    console.log('div의 class속성:', $('#div').get(0).class);  //undefined 없어..
    console.log('div의 class속성:', $('#div').get(0).className); //bg
    })

3.속성 제거

 $('#remove').click(function(){  
    $('div').removeAttr('class').removeAttr('style');  //제거 잘 됨
    $('div').removeProp('class').removeProp('style');   //제거 안됨
})

 

 

연습!

<div id="div" >DIV태그</div>		
<button id="1">1번 이미지</button>
<button id="2">2번 이미지</button>
<button id="3">3번 이미지</button>
<button id="4">4번 이미지</button>
<br />
<img src="#" alt="이미지" /><br />
<a>href속성을 미 지정한 A태그</a><br />
<input type="text"	size="30" />
<input value="확인" type="button" id="button" />

<hr />
<input type='checkbox' />체크박스
<a href="#" id="atag">A태그</a>
<input type="button" id="chkbtn" value="attr및 prop으로 체크 설정하기" />

버튼의 속성 (id값 ) 가져와서 이미지 변경하기

 $('button').click(function(){
    $('img').attr('src','../images/'+this.id+'.jpg');
})

 

value속성이없는type=text의 값읽어오기 : val()이 유리

 $('#button').click(function(){
    console.log('attr():',$(':text').attr('value'));
    console.log('prop():',$(':text').prop('value'));
    console.log('val():',$(':text').val());  //value속성을 함수로 만들어 놓은것
});

attr만 못 읽어 옴

 

동적으로 체크하기(체크 되어 있으면 해제, 해제되어 있으면 체크 )

$('#chkbtn').click(function(){
    if($(':checkbox').prop('checked'))
        $(':checkbox').prop('checked',false);
    else 
    $(':checkbox').prop('checked',true);


    if($(':checkbox').attr('checked'))
        $(':checkbox').attr('checked',false);
    else 
        $(':checkbox').attr('checked',true);
})

 


[TextHtml]

[시작태그와 종료태그 사이의 컨텐츠 읽어 오기]
    text()혹은 html();
    html()함수는 태그 포함 모든 내용을 읽어오고
    text()함수는 태그부분 제외한 텍스트 부분만 읽어옴

 [시작태그와 종료태그 사이의 컨텐츠 출력하기]
    text("설정할 문자열")혹은 html("설정할 문자열");
    html()함수는 출력시 태그가 해석 되서 출력됨.
    text()함수는 태그가 그대로 출력됨.

 

헷깔리네...

<fieldset>
    <legend>string text() 및 string html()함수</legend>
    <button id="read">읽기</button>
    <button id="write">쓰기</button>
    <button id="img">이미지 추가</button>
    <button id="btnText">버튼태그사이의 텍스트 얻기</button>
    <div><h2>제목입니다.</h2></div>
    <div id="display"></div>
</fieldset>

 

$('button').click (function(){
    switch(this.id){
        case 'read':
            var html=$('div:eq(0)').html(); 
            var text=$('div:eq(0)').text(); 
            console.log('html():%s,text():%s',html,text)
            break;
        case 'write': 
           // $('#display').html('<h3>시작태그와 종료태그사이에 넣기</h3>');  //글씨만 나옴
              $('#display').text('<h3>시작태그와 종료태그사이에 넣기</h3>');  //태그가 그대로 나옴
         break;
        case 'img' : 
        $('#display').html("<img src='../images/1.jpg' alt='이미지'/>")
            break;
        default : console.log($(this).html())
    }
 });

이미지는 읽어올 수가 없으니 alt인 이미지가 출력되고 콘솔창에 주소가 출력 됨


[EachIndex]

index():부모 자식 구조 안에서의 인덱스를 의미 !!! 인덱스 당연히  0부터 시작하고

 한 집안 내 에서의 서열?을 의미한다.... 

<fieldset>
    <legend>each(콜백함수)함수 및 index()함수</legend>
    <div>DIV1</div>
    <div>DIV2</div>
    <div>DIV3</div>
    <div>DIV4</div>
</fieldset>
<div>DIV5</div>

구조안에서의 관계를 잘 생각해!!

var clickDiv = $('div').click(function(){
    console.log('클릭한 div의 인덱스:',$(this).index());  
    //DIV1을 클릭했는데 인덱스가1임 ??!!  DIV5를 클릭하면 인덱스가 1!!!!! 
});

DIV1은 부모가 fieldset 이고 두 번째 자식이니까 인덱스가 1

DIV5는 부모가 body이고 얘도 두 번째 자식이라서 인덱스가 1

 

console.log(clickDiv); // 클릭이벤트가 걸린 모든 div   { 0: div, 1: div, 2: div, 3: div, 4: div 총 5개 !}
console.log(clickDiv.html());  //무조건 1번째요소의 컨텐츠만 가져옴  이때! each함수 사용!

clickDiv.each(function(index,element){   //요 element는 자바스크립트DOM객체!
    console.log('index:',index, ',element:',element.innerHTML)
});

 

 

var colors=['#ff0000','#00ff00','#0000ff','#89afbc','gray'];
    $('div').each(function(index,item){
        $(item).attr({style:"background-color:"+colors[index]}); 이렇게해도 되고
        $(this).attr({id:"div"+index,style:"background-color:"+colors[index]}); 요렇게도 되고
    })

    //동적으로 부여된 아이디값으로 선택. 오 신기
    console.log($('#div0').prop('style'));  //CSS2Properties { "background-color" → "rgb(255, 0, 0)" }
    console.log($('#div0').attr('style'));  //background-color:#ff0000

    //hover적용
    $('div').each(function(){
        //원래 배경색
        var bgColor=$(this).css('backgroundColor');

        $(this).hover(function(){
            $(this).css('backgroundColor','yellow');
        },function(){
            $(this).css('backgroundColor',bgColor);
        })
    });

 

WidthHeight

 

****** width()나 height() 혹은 css("속성명")으로 가로폭 세로폭을 얻을 때는 마진 및 패딩 그리고 보더 값이 
        미 포함됨  값임. outerWidth(),outerHeight()로 얻을 때 (디폴트:false) 패딩값하고 보더값이 포함됨.
       true로 설정 시에는 마진값도 포함 됨.

<fieldset>
    <legend>width(),height(),outerWidth(),outerHeight()</legend>
    <div></div>
    <button>가로폭/세로폭 구하기</button>
</fieldset>

이건 걍 한 방에 가쟈

$(function(){
    var div=$('div');
     
     패딩.테두리,마진 모두 포함 안됨
     var width = div.width();
     var height = div.height();

     패딩.테두리 포함
     var outerWidth = div.outerWidth();
     var outerHeight = div.outerHeight();

     패딩.테두리,마진 모두 포함 
     var outerWidthWithMargin = div.outerWidth(true);
     var outerHeightWithMargin = div.outerHeight(true);

     $('button').click(function(){  
        parseInt 할 필요 가 없음 그냥 숫자만 나옴
        console.log('가로폭:%s,세로폭:%s(마진/패딩/보더 미 포함)',width,height);
        console.log('가로폭:%s,세로폭:%s(마진만 미 포함)',outerWidth,outerHeight);
        console.log('가로폭:%s,세로폭:%s(마진/패딩/보더 미 포함)',outerWidthWithMargin,outerHeightWithMargin);
      css속성명으로 얻기 (단위 포함)
    console.log('가로폭:%s,세로폭:%s(css()함수)',parseInt(div.css('width')),div.css('height'));
    });   
 });

 

 


[ShowHide]

말 그대로 클릭 시 숨겼다 보였다 

show() 보였다

hide() 숨겼다

요거 두 개 합친 기능이 toggle()함수임!

 

폼 

<fieldset>
    <legend>show(),hide()함수</legend>
    <div id="accordion"><!-- 제이쿼리 UI적용시 추가DIV -->
        <div class="title"><h2>제목1</h2></div>
        <div class="content">
            내용입니다1<br/>
            내용입니다1<br/>
            내용입니다1<br/>
        </div>
        <div class="title"><h2>제목2</h2></div>
        <div class="content">
            내용입니다2<br/>
            내용입니다2<br/>
            내용입니다2<br/>
        </div>
        <div class="title"><h2>제목3</h2></div>
        <div class="content">
            내용입니다3<br/>
            내용입니다3<br/>
            내용입니다3<br/>
        </div>
    </div>
</fieldset>

 

 $(function(){
        페이지 최초 실행 시 숨기기
        $('.content').hide();   //style='display:none ;' 검사창 보니 이렇게 적용되네!

        제목 클릭 시 내용 보이기
        1.show()함수 사용 
       $('.title').click(function(){
           $(this).next().show();  //이렇게 하면 너무 밋밋함
           $(this).next().show(500,function(){  //이렇게 하면 애니메이션처럼 효과 넣을 수 있음 ! 
                $(this).css('backgroundColor','yellow');  // function안에서의this는  $(this).next()임 title의 this 아님 !!
           });              
        })

		 2.토글 함수 사용
         $('.title').click(function(){
            $(this).next().toggle(500,function(){  
                $(this).css('backgroundColor','yellow');
           });              
        })

         3.toggle함수 미 시용  show랑hide 함수로 아코디언 효과
        $('.title').click(function(){   //내용이 숨겨져 있으면 보여주고 보여주고 있으면 숨기고               
           if($(this).next().css('display') === 'none'){
                $('.content').hide(300);
                $(this).next().show(300);
            }
           else
                $(this).next().hide(300);           
       })
 })

이럴 줄 알고 

제이쿼리는 아코디언 함수를 준비 해 놨다...

$( "#accordion" ).accordion({
     collapsible: true,
     active: 0
 });

한 방이면 끝남.... 허무...

 


SlideUpDown

이건 위랑 너무 기능이동일해서.... 보이는 애니메이션 효과만 조금 다를 뿐?

 <fieldset>
    <legend>slideDown(),slideUp(),slideToggle()함수</legend>	
        <h2 class="title">제목1</h2>
        <div class="content">
            내용입니다1<br/>
            내용입니다1<br/>
            내용입니다1<br/>
        </div>
        <h2 class="title">제목2</h2>
        <div class="content">
            내용입니다2<br/>
            내용입니다2<br/>
            내용입니다2<br/>
        </div>
        <h2 class="title">제목3</h2>
        <div class="content">
            내용입니다3<br/>
            내용입니다3<br/>
            내용입니다3<br/>
        </div>
    </div>
</fieldset>

똑같으니까 한 큐에 가요

$(function(){ 
        페이지 최초 시는  숨겨
        $('.content').hide();

       1.SlideDown()함수 사용
       $('.title').click(function(){
           $(this).next().SlideDown(); 이것 밋밋
           $(this).next().slideDown(200 , function(){  약간의 애니메이션?
                $(this).css('backgroundColor','yellow');
           });              
        })

        2.slideToggle -slidedown/up 동시구현
        $('.title').click(function(){
            $(this).next().slideToggle(500,function(){  
                $(this).css('backgroundColor','yellow');
           });              
        })

         3.slideToggle() 함수 미시용  slidedown 랑 slideup 함수로 아코디언 효과
          $('.title').click(function(){   //내용이 숨겨져 있으면 보여주고 보여주고있으면 숨기고               
           if($(this).next().css('display') === 'none'){
                $('.content').slideUp(300);
                $(this).next().slideDown(300);
            }
           else
                $(this).next().slideUp(300);           
          });
    });

[FadeInOut] 

얘도 똑같.... 폼도 완전 같으니 폼도 생략

$(function(){ 
        페이지 최초 시는  숨겨
        $('.content').hide();

        1.fadeIn()함수 사용
        $('.title').click(function(){
           // $(this).next().fideIn();
           $(this).next().fadeIn(300 , function(){  
                $(this).css('backgroundColor','yellow');
           });              
        })

          2.fadeToggle -fadeIn/out 동시구현
        $('.title').click(function(){
            $(this).next().fadeToggle(500,function(){  
                $(this).css('backgroundColor','yellow');
           });              
        })

        3.FadeToggle함수 미시용  FadeIn 랑 FadeOut 함수로 아코디언 효과
          $('.title').click(function(){   //내용이 숨겨져 있으면 보여주고 보여주고있으면 숨기고               
           if($(this).next().css('display')=== 'none'){
                $('.content').fadeOut(500);
                $(this).next().fadeIn(500);
            }
           else
                $(this).next().fadeOut(500);           
          });

    });

next()/prev()

같은 형제 계열 중 에서 전/후 요소 선택하기

자바스크립트에서 

nextElementSibling와 previousElimentbling 를 사용하는 것과 같음

 

우선폼 먼저

 <fieldset>
    <legend>next() 및 prev()함수</legend>
    <button id="next">다음</button>
    <button id="prev">이전</button>
    <button id="continue" >계속</button>
    <ul>
     <li>JAVA</li>
     <li>JSP</li>
     <li id="third">FRAMEWORK</li>
     <li>JQUERY1</li>
     <li>JQUERY2</li>
     <li>JQUERY3</li>		
     <li>JQUERY4</li>
    </ul>			
 </fieldset>

id 속성이 있는 framework를 기준으로 속성을 줄거

next()

다음 버튼을 누르면 framework의 다음 글자에 css속성을 넣을 거임

$('#next').click(function(){
	 	제이쿼리 사용 시 한줄이면 끝
     $('#third').next().css({color:'red',fontSize:'1.8rem'});
        
        위 코드를 바닐라를 사용하면
        var third =document.querySelector('#third');
        var nextSibling = third.nextElementSibling;
        nextSibling.style.color='red';
        nextSibling.style.fontSize='1.8em';
            =>css속성 주는건 한줄로 줄이는게 가능
            nextSibling.style="color:red;font-size:1.8em";
             ==> setattribute 함수를 사용해도 가능
     		nextSibling.setAttribute('style','color:red;font-size:1.8em');
    });

 

prev()

이건 이전 형제들을 선택하는 함수

역시 기준은 framework로 잡고 구현

$('#prev').click(function(){
		제이쿼리사용
       $('#third').prev().css({color:'red',fontSize:'1.8rem'});
        
        바닐라 js로 변경시는 nextSibling을 previousElimentbling로 만 변경
       var third =document.querySelector('#third');
       var prebSibling = third.previousElimentbling;
       prebSibling .style.color='red';
       prebSibling .style.fontSize='1.8em';
 });

 

null혹은 undefined가 아닌 제이쿼리 객체를 무조건반환! 
 ******그래서 찾을 요소가 없는 것은 length로 판단한다!********

$('#continue').click(function(){
   console.log($('#third').prev().prev().html())   // JAVA가 잘 나옴
   console.log($('#third').prev().prev().prev().html())  // undefined가 나옴 이전이 없으니까

	console.log($('#third').prev().prev().prev())  //Object { length: 0, prevObject: {…} } 오잉?
 	console.log($('#third').prev().prev().prev().length == 0 )  //true 
});

 

//문제!

    //첫 번째 li 객체 저장
    var liObj = $('li:first');
    //마지막 객체여부 판단용 변수
    var index = 0;
    //li 객체의 전체수
    var length =$('li').length;

$('#continue').click(function(){   
    //index가 0일 때 즉 최초 버튼클릭 시
    if(index===0) $('li:last').css({color:'black',fontSize:'1em'});
   
   else{//이전 li객체를 원래대로
        liObj.prev().css({color:'black',fontSize:'1em'});
    }
    //해당 li객체를 css변경
    liObj.css({color:'red',fontSize:'1.8rem'});
    //인덱스 증가
    index++
    if(index != length)
   		liObj = liObj.next();
    else{
        //인텍스 다시 0
        index=0;
        //liObj에 처음 li객체를 저장
        liObj = $('li:first');
  }

});

 


[Siblings()]

siblings() : 모든 형제들 요소를 반환 한다.

폼 먼저

<fieldset>
    <legend>siblings([선택자])</legend>
    <div>
      <span>Hello</span>
    </div>
    <p class="selected">Hello Again</p>
    <p>And Again</p>
</fieldset>

 

 //요 둘의 차이는 자신을 포함 하느냐 안하느냐
 console.log($('p').siblings());  // 0: legend, 1: div, 2: p.selected, 3: p 요렇게 총 4개나옴
 console.log($('p.selected').siblings()); //Object { 0: legend, 1: div, 2: p} 요렇게 총 3개

 

$(p.selected)를 요렇게도 표현 가능하넴

$('div').siblings('.selected').css('background-color','yellow')

적용 잘 됨

each 함수적용도 가능함

each()함수 : 요소 하나하나에 함수를 적용시키겠다...

$('p').siblings().each(function(index,item){  
        ******item은 자바스크립트 객체이다!!!(제이쿼리객체가아님)
          //  console.log(item.innerHTML); 찍어보면 <span>Hello</span> 가 나옴
        if(item.nodeName ==='DIV')
            console.log(item.firstElementChild.innerHTML);  //콘솔창에 span태그 없애려고 나눔 !!
        else
            console.log(item.innerHTML);
     });

 


Parent

부모요소 얻기

 

<fieldset>
    <legend>parent([선택자])함수</legend>
    <button>부모얻기</button>

    <div class="div">
      <div>자식1</div>
      <div >자식2</div>
      <div class="third">자식3</div>
    </div>
    <ul>
     <li>JAVA</li>
     <li>JSP</li>
     <li class="third">FRAMEWORK</li>
     <li>JQUERY1</li>
     <li>JQUERY2</li>
     <li>JQUERY3</li>		
     <li>JQUERY4</li>
    </ul>	
 </fieldset>

 

부모찾기

 $('button').click(function(){
        console.log($('.third').parent())  // Object { 0: div.div, 1: ul, length: 2} 2개얌
        //모든 부모에 배경색 지정
        $('.third').parent().css('background-color','yellow');
        //부모중 div만 배경색 지정 () 안에만 지정해 주면 되넴?!!
        $('.third').parent('.div').css('background-color','yellow');

        //div는 배경색, 콘솔에는 버튼의 컨텐츠 출력! 한 번에 적용 됨! 오 짱신기
     console.log($('.third').parent('.div').css('background-color','yellow').prev().html())

    	 위를 바닐라로 
     console.log(document.querySelectorAll('.third')); // 타입확인 NodeList [ div.third, li.third ]
    document.querySelectorAll('.third').forEach(function(item){
        console.log(item.parentElement); div랑 ul 태그가 같이 나오넴
        console.log(item.parentElement.nodeName);   // 진짜 div랑 ul 글자만 나옴
        if(item.parentElement.nodeName== 'DIV'){
            item.parentElement.style.backgroundColor='yellow';
            console.log(item.parentElement.previousElementSibling.textContent);
        }          
    })
 });

 

 

이건 형제요소 찾기 연습인듯

<h2>형제요소찾기 연습</h2>
<input type="text" />	
<input type="button" value="등록" />	
<hr/>
<table cellspacing="1" bgcolor="gray" width="60%">
        <tr bgcolor="white">
            <th>번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>작성일</th>
    <th>삭제</th>
        </tr>
        <tr bgcolor="white" title="1">
            <td>1</td>
            <td>제목1</td>
            <td>작성자1</td>
            <td>2013-9-12</td>
    <td><input type="button" class="delete" value="삭제"/></td>
        </tr>
        <tr bgcolor="white" title="2">
            <td>2</td>
            <td>제목2</td>
            <td>작성자2</td>
            <td>2013-9-12</td>
    <td><input type="button" class="delete" value="삭제"/></td>
        </tr>
        <tr bgcolor="white" title="3">
            <td>3</td>
            <td>제목3</td>
            <td>작성자3</td>
            <td>2013-9-12</td>
    <td><input type="button" class="delete" value="삭제"/></td>
        </tr>
        <tr bgcolor="white" title="4">
            <td>4</td>
            <td>제목4</td>
            <td>작성자4</td>
            <td>2013-9-12</td>
            <td><input type="button" class="delete" value="삭제"/></td>
        </tr>
  </table>

 

 

***댓글 게시판 에서 댓글수정 시 사용했던 코드 여기있다 !!!!******

  	테이블에 마우스오버 기능
$('tr').slice(1).hover(function(){
    $(this).css({backgroundColor:'yellow',cursor:'pointer'});
},function(){
    $(this).css({backgroundColor:'white'});
})

테이블에 클릭 기능 이거!!!!! 게시판 만들 때 댓글 수정에 적용한 그거 !!!!****
$('tr').slice(1).click(function(){
    $('input[type=text]').val($(this).children(':eq(1)').html());
    $('input[type=button]').filter('[value=등록]').val('수정');   //필터 쓴 거 잘보고 
})

$('.delete').click(function(){
    console.log('삭제하려는 글 번호:',$(this).parent().prev().prev().prev().prev().html()); 이것은 노가다
    console.log('삭제하려는 글 번호:',$(this).parent().siblings(':eq(0)').html);  //형제들 중 첫 번째
    console.log('삭제하려는 글 번호:',$(this).parent().siblings(':first').html()); // 동일
})

 

[Hover]

마우스오버/아웃 효과

 

폼먼저

<fieldset>
    <legend>hover(콜백함수1,콜백함수2)</legend>
    <table cellspacing="1" bgcolor="gray" width="60%">
        <tr bgcolor="white">
            <th>번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>작성일</th>
        </tr>
        <tr bgcolor="white">
            <td>1</td>
            <td>제목1</td>
            <td>작성자1</td>
            <td>2013-9-12</td>
        </tr>
        <tr bgcolor="white">
            <td>2</td>
            <td>제목2</td>
            <td>작성자2</td>
            <td>2013-9-12</td>
        </tr>
        <tr bgcolor="white">
            <td>3</td>
            <td>제목3</td>
            <td>작성자3</td>
            <td>2013-9-12</td>
        </tr>
        <tr bgcolor="white">
            <td>4</td>
            <td>제목4</td>
            <td>작성자4</td>
            <td>2013-9-12</td>
        </tr>
    </table>
    <hr />
    <img src="../images/1.jpg" alt="이미지"
        style="width:100px; height:100px" />
</fieldset>

 

 

비교를위해

mouseover()함수와 mouseout()함수로 구현

$('tr').slice(1).mouseover(function(){
    $(this).addClass('bg');
}).mouseout(function(){
    $(this).removeClass('bg');
});

hover()함수로 구현

.hover(function(){ 마우스오버 시 },function(){ 마우스아웃 시 })

 $('tr').slice(1).hover(function(){
    $(this).addClass('bg');
},function(){
    $(this).removeClass('bg');
});

 

이미지위에 마우스오버시 2.jpg로 마우스 아웃시 1.jpg

 $('img').hover(function(){
    this.src="../images/2.jpg"
},function(){
    this.src="../images/1.jpg"
});

 

문제.  이미지에 마우스 오버시 이미지 크기를  가로폭은 2배
           세로폭 1.5배로 마우스 아웃시에는 원래 크기로... 하드코딩 노노

var width = parseInt($('img').get(0).style.width);
var height = parseInt($('img').get(0).style.height);

$('img').hover(function(){
    this.style.width = width*2+'px';
    this.style.height=height*1.5+'px';
},function(){
    this.style.width=width+'px';
    this.style.height=height+'px';
});

 


 

[One]

이벤트를 한 번만 실행할 때

이거도 짧아서 한번에

<script>
 $(function(){
    $('button:first').one('click',function(){
        console.log('딱 한번 만 실행')
    });
    $('button:last').on('click',function(){
        console.log('클릭 할 때마다 실행')
    });
 });
</script>

<body>
 <fieldset>
    <legend>one('이벤트명',콜백함수)</legend>
    <button>한번만 실행</button>
    <button>여러만 실행</button>
 </fieldset>
</body>

 

 


[CSS]

css제어하기

 <fieldset >
    <legend>string css("css속성명"),jQuery css("css속성명","속성값")</legend>
    <span style="color:green;font-size:1.2em"></span>		
    <div style="width:100px;height:100px;background-color:red"></div>
    <button id="get">속성값 읽기</button>
    <button id="set">속성값 설정</button>
 </fieldset>

[CSS 속성 값 읽기]- css("css의 속성명")

 $('#get').click(function(){
    var div = $('div');
    var width = div.css('width');
    var height = div.css('height');
    console.log('가로:%s, 세로:%s',width,height);

   속성명 그대로
  var back = div.css('background-color'); 
    자바스크립트방식
  var back = div.css('backgroundColor'); 
   console.log('배경색(제이쿼리)',back);
   console.log('배경색(바닐라)',div.get(0).style.backgroundColor);
   $('span').html('가로폭:'+width+'세로폭:'+height+'배경색:'+back);
});

 

[CSS 속성 설정]- css("속성명","설정할 값")

단위 생략시 무조건  px이 기본 단위이다.

$('#set').on('click',function(){
    메소드체인방식
    $('div').css('width','200px').css('height','200').css('background-color','green');
    JSON타입으로
    $('div').css({width:'200px',height:'200px',backgroundColor:'green'})
});

 

 

최종보스

폼 대로 제어하기

<a href="#">크게</a> | <a href="#">작게</a> | <a href="#">진하게</a>
| <a href="#">보통</a> | <a href="#">빨강</a> | <a href="#">그린</a>
| <a href="#">검정</a>  | <a href="#">기울이기</a> | <a href="#">똑바로</a>
<p id="article" style="font-size:12px">
  기사 내용입니다<br/>
  기사 내용입니다<br/>
  기사 내용입니다<br/>
  기사 내용입니다<br/>
  기사 내용입니다<br/>
</p>
var a= $('a').click(function(){  //힌트
    console.log('반환값 A:',a); //클릭 이벤트가걸린 모든 a 태그
    console.log('클릭한 A태그의 컨텐츠:',$(this).html());
    console.log('무조건 첫 번째 컨텐츠:',a.html());  //무조건 첫 번째 컨텐츠만 나옴           

//답  요건 내가 한거지롱
var fontSize=parseInt($('#article').css('fontSize'));
    switch($(this).html()){
        case "크게":$('#article').css('fontSize',fontSize+5+'px'); break;
        case "작게":$('#article').css('fontSize',fontSize-5+'px'); break;
        case "진하게":$('#article').css('font-weight','bold'); break;
        case "보통":$('#article').css('font-weight','normal'); break;
        case "빨강":$('#article').css('color','red'); break;
        case "그린":$('#article').css('color','green'); break;
        case "검정":$('#article').css('color','black'); break;
        case "기울이기":$('#article').css('font-style','italic'); break;
        default :$('#article').css('font-style','normal'); break;
    }      
})

[Toggle]

전에 했던 토글토글이랑은 조금 다름

그냥 없어졌다가 나타나는 그런 토글임

.toggle( ) 요렇게 적용하는게 기본 

 

폼을 보고

 <style>
    div {
      width: 100px;
      height: 100px;
      background-color: green;
      border: 1px red solid;
      font-style: normal;
      font: 900;
    }
 </style>

<body>
    <fieldset>
		<legend>toggle([Duration][,콜백함수])함수 첫번째:토글링을 걸을 요소가 하나</legend>
		<div id="div"></div>
		<button>안보이기</button>
	</fieldset>
	<fieldset>
		<legend>toggle([Duration][,콜백함수])함수 두번째:토글링을 걸을 요소가 두개</legend>
		<!--전제 조건:무조건 하나는 display:none
        그리고 두 요소의 클래스명 동일하게
    -->
    <div class="div" style="background-color: red"></div>
	<div class="div" style="display: none; background-color: green"></div>
	<button>토글링</button>
	</fieldset>   
</body>

 

토글링 걸을 요소가 하나 일 때(보였다 안보였다)

 $('button:eq(0)').click(function(){
   이건 애니효과가 없음
   $('#div').toggle();    애니효과가없음
     var div = document.querySelector('#div');
     console.log(div.style.display==='');
      if(div.style.display==='') 
        div.style.display ==='none';
      else 
        div.style.display ==='';
                
    애니효과를 넣어 보자
 	var button = $(this);
    $('#div').toggle(
        2000,   //토글링 걸리는 시간
        function(){
            var text = button.html();  
            console.log('토글링완료:',text);
            button.html(text==='안보이기'?'보이기':'안보이기')  //버튼텍스트도 변경
    });

 });

 

토글링 걸을 요소가 두 개 일 때(두 요소가 번갈아 가며 보이기)

  $('button:last').click(function(){
    $('.div').toggle(2000);
 });
 두개가 번갈아 가면 toggle되니까 더 간단

[ToggleClass]

.toggleClass('속성명')

제이쿼리의 removeClass()/addClass()를 하나의 함수로 구현

간단하니까 그냥 한 번에

 스타일
 <style>
    div{
      width:100px;
      height: 100px;
      background-color: green;
    }
    .invisible{
      display:none;
    }
</style>

코드    
 <script>
    $(function(){
        $('button').click(function(){
            //제이쿼리의 removeClass()/addClass()를 하나의 함수로 구현
            $('div').toggleClass('invisible');
            $(this).html($(this).html()==='안보이기'?'보이기':'안보이기');
        })
    });
</script>

폼   
<body>
    <fieldset>
        <legend>toggleClass('클래스명')</legend>
        <div></div>
        <button>안보이기</button>
    </fieldset>
</body>

 

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

12/19 67-1 [JQuery] next/prev/Siblings/Parent  (0) 2022.12.19
12/16 66-6 [JQuery] hover/one/css  (0) 2022.12.17
12/16 66-4 [JQuery] slice/filter  (0) 2022.12.17
12/16 66-3 [JQuery] trigger/LiveDie  (1) 2022.12.17
12/16 66-2 [JQuery] get/bind  (0) 2022.12.16

[Slice]

이번엔 스타일도 폼으로 빼 놓고 코드로 적용시키겠

폼을 봅니다.

<style>
    .bg {
      background-color: green;
      font-size: 1.4em	
    }
    div{
      width:100px;
      height:100px;
      text-align:center;
      line-height: 100px;
      border:1px red solid	
    }
</style>

<body>
<fieldset>
    <legend>slice(시작인덱스[,끝인덱스])</legend>
    <button>색상변경</button>
    <div class="bg">DIV1</div>
    <div>DIV2</div>	
    <div>DIV3</div>	
    <div>DIV4</div>	
    <div>DIV5</div>
    <div>DIV6</div>	
    <div>DIV7</div>	
</fieldset>
</body>

 

1.slice(인덱스) : 인덱스 부터 끝까지 적용

addClass는 동적으로 class 속성을 넣어버림

저 밑의 코드는 결국 폼에서

<div class="bg">DIV3</div> 

<div class="bg">DIV4</div> 

...

<div class="bg">DIV7</div> 

처럼 변경된거랑 같은 거!

 $('div').slice(2).addClass('bg')

 

2.slice(시작,끝)  : 시작서부터 끝까지 적용

$('div').slice(2,$('div').length).addClass('bg')

 

3.음수면 밑에서 부터. n개

 $('div').slice(-4).addClass('bg')

 

****적용한 요소를 없앨 때는 removeClass(' ')

$('div').removeClass('bg')

 

문제 

아 나도 거의 다 풀었는데.. 아쉽

  내가한거
var i=0;       
$('button').click(function(){                    
    i++     
    console.log(i)   
    $('div').slice(i-1).removeClass('bg')
    $('div').slice(i).addClass('bg')
    $('div').slice(i+1).removeClass('bg')                              
    if(i == $('div').length) i=-1;                       
});


 답
var index=1;       
$('button').click(function(){
    $('div').slice(index-1).removeClass('bg')
    $('div').slice(index,index+1).addClass('bg')
    index++;
    if(index == $('div').length) index=0;

})

 


[Filter]

생각하는 그 필터가 맞음

필터링해서 적용시키기

 폼 먼저 보자

<style>
    .bg{
      background-color: black;
      color:white;
      font-weight: bold;
      text-decoration: none;
    }
    .border{
      border:2px red solid
    }
</style>

<body>
    <fieldset>
		<legend>$(선택자).filter("선택된 DOM객체중 가져올 객체 선택자")</legend>
		<a href="www.naver.com" >네이버</a>
		<a href="www.nate.com" >네이트</a>
		<a href="www.daum.net" >다음</a>
	</fieldset>
</body>

.filter(' ') 로 필터링하고

.end() 는 마지막제 적용 했던 필터 전 으로 이동 !!

<script>
    $(function(){
        $('a').addClass('bg')    //선택된  모든 a 태그에 class="bg"추가
        .filter('[href*=nate]')  //선택된  모든 a 태그 중 속성값이 nate인 것에  border추가
        .addClass('border')  
        .end()    //nate가 포함된 a 태그 바로 직전에 선택된 객체로 이동  ***
        .filter(':eq(2)')     //선택된 모든 a 태그중에 인덱스가 2인태그
        .removeClass('bg').css('font-size','1.8em');
    });
</script>

 

 

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

12/16 66-6 [JQuery] hover/one/css  (0) 2022.12.17
12/16 66-5 [JQuery] Toggle/ToggleClass  (0) 2022.12.17
12/16 66-3 [JQuery] trigger/LiveDie  (1) 2022.12.17
12/16 66-2 [JQuery] get/bind  (0) 2022.12.16
12/16 66-1 [JQuery] 개념+Select  (1) 2022.12.16

+ Recent posts