2Bbear's knowledge workshop

jquery는 자바스크립트를 좀더 손쉽게 사용하기 위해 만들어진 자바스크립트 라이브러리 중 하나이다.

자주 쓰이는 로직들을 랩핑해두었다고 생각하면 된다.

또 셀렉터를 이용해서 원하는 요소를 지정할 때 쓰이는 document.getElementsByID등을 $(Selector), jQuery(Selector) 형식으로 표현할 수 있으므로 코드도 짧아지게 된다.


- jQuery를 다운로드하는 방법

 https://jquery.com/download/에 접속하여 원하는 버전을 다운 받습니다.


저는 https://code.jquery.com/jquery-3.3.1.min.js 를 다운 받았습니다. 

근대 이런게 뜨내요...그래요 이게 jquery-3.3.1.min.js 입니다. 이걸 어떻게 다운 받으시면 되고 저 같은 경우는 다운 받는 방법을 모르니 그냥 복사 한다음에 메모장에 넣고 그 뒤에 js확장자로 변경하겠습니다.


그렇게 파일을 만들고 자신의 웹 프로젝트에 js 디렉토리를 만든다음에 그 안에 파일을 넣어줍시다.


-jQuery를 사용하는 방법

다운받은 js 파일을 이용할 경우

<head>

 <script src="js/jquery-3.1.0.min.js"></script>

<head> 

제이쿼리를 쓰기 위해서는 head 부분에 사용선언을 해주어야 합니다.


CDN을 이용할 경우

<head>

 <script src="http://code.jquery.com/jquery-latest.min.js"></script>

<head> 

또는 사용 가능한 url을 가져다 써도 됩니다.

<head>

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<head> 


그냥 파일로 하면 오류 발생할 경우가 많으니까 CDN 씁시다.


테스트를 해봅시다

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>

$(function(){

        $('h3').html("jquery test");

     });

</script>

<title>Insert title here</title>

</head>

<body>

<script>

 

</script>

<h3>hello hi</h3>

</body>

</html>

이 코드를 이렇게 쓰면 .h3안에 있는 hello hi가 안나오고 jquery test가 나옵니다.



- 기본 사용법


제이쿼리는 CSS처럼 selector를 가집니다.

$(selector).action(); 이 기본 형태입니다.


selector는 시작 부분에 언급한 것 처럼, document.getElementById에서 getElementById를 맡고 있다고 보면 됩니다. 


아이디는 #id 클래스는 .class로 html 태그는 p로 표현하면 됩니다. 응용해서 특정 클래스 내의 모든 html태그에 적용시키려면 .className div 이런 식으로 사용하게 됩니다.

간단한 예제

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Tutorial test</title>

    <script src="http://code.jquery.com/jquery-latest.min.js"></script>

    <script>

        $(function(){

            $('#first').css("color","red");

            $('.second').css("color","blue");

            $('p').css("color","yellow");

        });

    </script>

</head>

<body>

    <div id="first">first is red</div>

    <div class="second">second is blue</div>

    <p>this is yellow</p>

</body>

</html>


action은 event가 될수도, effect, html이 될 수도 있습니다. 말 그대로 액션을 일어나게 하기 위해 쓰이는 부분입니다. 위의 예시에서 $(funtion(){}); 이라는 구조가 나왔는데 이것은 웹 페이지의 html이 모두 출력되면 바로 실행 된다는 뜻으로, $(document).ready(funtion(){}); 과 같은 의미입니다. 여기서 readt() 역시도 action()의 하나 입니다.


event

마우스로 요소를 옮기는 것, 클릭하는 것 등의 모두가 이벤트라 할 수 있다.

간단한 click 이벤트를 알아보자

$(selector).clock(); 이렇게 사용된다.


 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Tutorial test</title>

    <script src="http://code.jquery.com/jquery-latest.min.js"></script>

    <script>

        $(function(){

            $('#first').css("color","red");

            

            $('.second').css("color","blue");

            $('.mybutton').click(function(){

            $('.second').css("color","green");

            });

            $('p').css("color","yellow");

            

        });

    </script>

</head>

<body>

    <div id="first">first is red</div>

    <div class="second">second is blue</div>

    <p>this is yellow</p>

    <button type="button" class="mybutton"></button>

    

</body>

</html>


버튼을 누르면 2번째 문장이 초록색으로 바뀐다.


hover

마우스 커서를 요소 위에서 왔다갔다 할 때 발생하는 이벤트이다.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Tutorial test</title>

    <script src="http://code.jquery.com/jquery-latest.min.js"></script>

    <script>

        $(function(){

            $('#first').css("color","red");

            

            $('.second').css("color","blue");

            $('.mybutton').click(function(){

            $('.second').css("color","green");

            });

            $('p').css("color","yellow");

            

            $('.selector').hover(function(){

            $('.second').css("color","blue");

          }, function(){

        $('.second').css("color","red");

          });

        });

    </script>

</head>

<body>

    <div id="first">first is red</div>

    <div class="second">second is blue</div>

    <p>this is yellow</p>

    <button type="button" class="mybutton"></button>

    <button type="button" class="selector"></button>

    

</body>

</html>


2번째 버튼에 마우스를 가져대면 2번째 문장의 색이 변하는 것을 확인 할 수 있다.


keypress 이벤트

키보드가 눌리면 발생된다.


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Tutorial test</title>

    <script src="http://code.jquery.com/jquery-latest.min.js"></script>

    <script>

        $(function(){

            $('#first').css("color","red");

            

            $('.second').css("color","blue");

            $('.mybutton').click(function(){

            $('.second').css("color","green");

            });

            $('p').css("color","yellow");

            

            $('.selector').hover(function(){

            $('.second').css("color","blue");

          }, function(){

        $('.second').css("color","red");

          });

            $('.myinput').keypress(function(){

            alert("keypress called");

            });

        });

    </script>

</head>

<body>

    <div id="first">first is red</div>

    <div class="second">second is blue</div>

    <p>this is yellow</p>

    <button type="button" class="mybutton"></button>

    <button type="button" class="selector"></button>

    <input type="text" class="myinput" ></input>

</body>

</html>

입력란에 뭔가 입력하려고 하면 경고창이 뜨게 된다.


display

글의 내용을 숨기거나 표시하거나 드롭다운 메뉴를 만들 수도 있고 등등의 효과를 구현할 수 있다.

show/hide

fadeIn/fadeOut

slideUp/slideDown 등이 잇다.


show/hide


 show([duration][,complete]);

hide([duration][,complete]);

duration과 complete는 각각 효과의 지속시간, 효교ㅘ가 완료 되엇을 때 실행될 funtion을 의미하는 것으로 optional한 부분이다. .duration의 경우 단위로는 1000ms가 1초가 되며 따로 지정해주지 않으면 400ms가 default값으로 가지게 된다. slow , fast로 쓸 수도 있는데 각각 600ms, 200ms를 의미한다.

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("#hide").click(function(){

    $("p").hide();

  });

  $("#show").click(function(){

    $("p").show();

  });

});

</script>

</head>

<body>


<p>If you click on the "Hide" button, I will disappear.</p>


<button id="hide">Hide</button>

<button id="show">Show</button>


</body>

</html>



버튼을 눌르면 글자가 사라지고 나타난다.


복잡하게 if문 쓰자면

function toggle_layer() {

if($("#layer").css("display") == "none"){

$("#layer").show();

}else{

$("#layer").hide();

}

}


이렇게 쓸 수 있고 


toggle을 이용하여 사용하는 방법도 있다

$("#tagID").toggle(); // show -> hide , hide -> show 




더 많은 API는 이곳에서 찾아 볼 수 있다.

https://oscarotero.com/jquery/




'WebDegine > Web' 카테고리의 다른 글

자바 서블릿을 사용해보자  (0) 2019.01.02
jQuery Plugin 사용법  (0) 2019.01.02
[CSS] 부트스트랩 사용법  (0) 2018.12.31