본문 바로가기
JAVASCRIPT/jQuery

[JQuery] 개념 정리 (prototype, navigator, off, attr, append, preventDefault, live, val 등 )

by sjs_2215 2019. 11. 10.

출처: DO IT 자바스크립트+제이쿼리 입문

jquery 공식 문서 : https://jquery.com/

엘리먼트 제어(여러 기능들): https://opentutorials.org/course/53/51 , https://api.jquery.com/category/manipulation/

'폼'을 제어하는데 필요한 이벤트와 메소드들: https://opentutorials.org/course/53/53, http://api.jquery.com/category/forms/

폼 - 서버로 데이터를 전송하기 위한 수단.


  • prototype function

메모리 절약을 위한 프로토타입 사용하기

: 객체 생성자 함수에 프로토타입을 사용하여 함수를 등록하면 메모리 낭비 줄일 수 있다.

 

prototype(=원형, 객체 생성자 함수)
-> prototype을 사용하여 등록한 함수는 원형(객체 생성자 함수)에서 생성된 객체를 '공유'할 수 있다. 즉, 여러 개의 함수를 등록할 필요가 없다.

 

기본 객체 생성자 함수 예제)

function 함수명(매개변수1,2,3) {
    this.속성명 = 새 값;
    this.함수명 = function() {
        자바스크립트 코드;
    }
}

var 참조 변수(인스턴스 네임) = new 함수명();

var 참조 변수 = {속성: 새 값, 함수명 : function() {...}}

 

prototype 사용 객체 생성자 함수 예제)

function 함수명(매개변수1,2,3) {
    this.속성명 = 새 값;
}

함수명.prototype.함수명 = function() {
    자바스크립트 코드;
}

var 참조 변수(인스턴스 네임) = new 함수명();

  • .attr() 메서드

= 선택한 요소에 새 속성을 생성하거나 기존의 속성을 변경할 때 또는 요소의 속성 값을 불러올 때 사용

ex) -> 버튼 클릭 시 url 바뀜, 버튼 클릭 시 name 바뀜

 

<html>
    <head>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

        <script type ="text/javascript">
            $(function(){
                $("#btn1").click(function(){
                    $("#urls").attr("href","https://www.naver.com");
                });

                $("#btn2").click(function(){
                    $("#texting").attr("name","changed");
                });
            });
        </script>
    </head>
    <body>
        <p> change url </p>
        <a href="https://www.google.com" id="urls">url</a>
        <button  name="attr1" id="btn1">hello</button>
        <p> change text </p>
        <h4 id="texting"> text </h4>
        <button name="attr2" id="btn2">hello2</button>
    </body>
</html>

 

실습 출처:

https://qkrrudtjr954.github.io/jquery/2018/01/25/jquery-attr.html


  • navigator 객체

= 현재 방문자가 사용하는 브라우저 정보와 운영체제 정보를 제공하는 객체

 

navigator 속성 종류 중 하나
navigator.userAgent: 브라우저와 운영체제의 종합 정보를 제공

 

/* navigator 객체 실습 - 현재 방문자가 사용하는 브라우저 정보와 운영체제 정보를 제공*/
        var a = navigator.userAgent; 
        console.log(a);

  • <a href="#"> 의 의미

https://m.blog.naver.com/PostView.nhn?blogId=sangnam18&logNo=110093842395&proxyReferer=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3D%26esrc%3Ds%26source%3Dweb%26cd%3D4%26ved%3D2ahUKEwjXj9i7_NblAhX-xosBHeawC1gQFjADegQIAhAB%26url%3Dhttp%253A%252F%252Fm.blog.naver.com%252Fsangnam18%252F110093842395%26usg%3DAOvVaw2ORGghWfQanGUGSzDYZmVW


  • input 태그
<input type="text" id="in_user_id"></input></br>

  • .off()

on()과 반대로 이벤트를 해제하는 메소드

 

//body 부분
<div>
  <button id="test">Click Event Remove!</button>
</div>

//script 부분
$('#test').off('click');
// 해당 엘리먼트의 클릭이벤트를 제거함


 

이처럼 이벤트를 바인딩하는 경우 성능 및 메모리에 영향을 미치기때문

-> '사용하지 않거나 제거가 필요한 경우'에 반드시 off()를 사용하여 제거해야 함

 

작은 어플리케이션의 경우 영향이 크지 않으나 큰 어플리케이션의 경우 그 차이가 클 수 있

 


  • substring()

.substring()은 문자열에서 특정 부분만 골라낼 때 사용하는 메서드

https://www.codingfactory.net/10429

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
  </head>
  <body>
    <script>
      var str = '123456789';
      document.write( '<p>' + str + '</p>' );
      document.write( '<p>Substring from 1 to 4 : ' + str.substring( 1, 4 ) + '</p>' );
      document.write( '<p>Substring from 0 to 4 : ' + str.substring( 0, 4 ) + '</p>' );
      document.write( '<p>Substring from 2 : ' + str.substring( 2 ) + '</p>' );
    </script>
  </body>
</html>


  • append

: 선택한 요소의 내용의 끝에 콘텐츠를 추가한다.

출처: https://www.codingfactory.net/10170

//문법
.append(content [,content])

//예시
//script 부분
            $("#div_").live("click", function(e){
                $("#console").append("<br>div clicked");
            });

            $("#p_").live("click", function(e){
                $("#console").append("<br>p clicked");
            });

            $("#span_").live("click", function(e){
                $("#console").append("<br>span clicked");
            });

//body 부분

        <div id="div_">
            DIV영역
                <p id="p_">
                    P영역
                    <span id="span_">SPAN영역</span>
                </p>
        </div>

        <section id="console"><br></section>            

  • preventDefault()

= 현재 이벤트의 기본 동작을 중단함.

출처: https://programmingsummaries.tistory.com/?page=64

 

a 태그의 기본 기능인 url 이동 기능이 실행되지 않게 한 코드

 

ex.)

//script부분
//DIV 영역에 클릭 이벤트 설정
$("#div_").on("click",function(event){
    $("#console").append("<br>DIV 클릭");
});

//P 영역에 클릭 이벤트 설정
$("#p_").on("click",function(event){
    $("#console").append("<br>P 클릭");
});

//A 영역에 클릭 이벤트 설정
$("#a_").on("click",function(event){
    $("#console").append("<br>A 클릭");

    //이벤트의 기본 동작을 중단한다.
    event.preventDefault();
});

//body부분
<div id="div_">
    DIV영역
    <p id="p_">
        P영역
        <a id="a_" href="http://www.google.co.kr" target="_blank">A영역 구글 링크</a>
    </p>
</div>

<section id="console"><br></section>

  • .on 대신 .live 사용 (jquery 버전 조심)

에러 해결방법 ->

https://stackoverflow.com/questions/21625231/on-is-not-a-function-jquery-error

//script 부분
/*.on은 jquery 1.7 이상 가능. 그대신 .live 사용*/
            $("#div_").live("click", function(e){
                $("#console").append("<br>div clicked");
            });

            $("#p_").live("click", function(e){
                $("#console").append("<br>p clicked");
            });

            $("#span_").live("click", function(e){
                $("#console").append("<br>span clicked");
                e.stopPropagation();
            });

//body 부분
        <div id="div_">
            <a href="#"  style="color: rgb(0, 0, 0); margin-right: 20px;">div 영역</a>
                <p id="p_">
                    <a href="#"  style="color: rgb(0, 0, 0); margin-right: 20px;">p 영역</a>
                        <span id="span_">
                            <a href="#"  style="color: rgb(0, 0, 0); margin-right: 20px;">span 영역</a>
                        </span>
                </p>
        </div>

  • $.getJSON

https://api.jquery.com/jQuery.getJSON/


var b = {
        id: "tempFrm",
        name: "tempFrm",
        action: a,
        method: "GET", "POST" 
    };
  • .removeclass()

선택한 요소의 클래스 값을 제거하는 메서드

https://www.codingfactory.net/10198

 

h1 요소에서는 bg 클래스를 제거하여 테두리만 남기고, h2 요소에서는 bg와 bd 클래스를 제거하여 배경색과 테두리를 없애는

 

ex)

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <style>
      .bg { background-color: #eeeeee; }
      .bd { border: 1px solid #666666; }
    </style>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      $( document ).ready( function() {
        $( 'h1' ).removeClass( 'bg' );
        $( 'h2' ).removeClass( 'bg bd' );
      });
    </script>
  </head>
  <body>
    <h1 class="bg bd">Lorem ipsum dolor.</h1>
    <h2 class="bg bd">Lorem ipsum dolor.</h2>
  </body>
</html>



  • document.createElement

태그를 생성하는 방법

var $div = $('<div>Hello</div>');
var div = document.createElement('div');
var text = document.createTextNode('Hello');
div.appendChild(text);

https://www.zerocho.com/category/jQuery/post/57ae9d8d5abdd01500840008


  • setAttribute와 .attr()

https://opentutorials.org/course/53/47

jquery는 .attr()사용

 

setattribute 예제

<html>
     <body>
         <a id="tutorial" href="http://jquery.com" target="_self">jQuery</a>
         <script type="text/javascript">
             var tutorial = document.getElementById('tutorial');
             tutorial.setAttribute('href', 'http://jquery.org');
             tutorial.setAttribute('target', '_blank');
             tutorial.style.color = 'red';
         </script>
     </body>
 </html>

 

attr 예제

<html>
    <body>
        <a id="tutorial" href="http://jquery.com" target="_self">jQuery</a>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script type="text/javascript">
            jQuery('#tutorial').attr('href', 'http://jquery.org').attr('target', '_blank').css('color', 'red');
        </script>
    </body>
</html>

 

jquery의 .attr()을 사용하여 더 좋은 점 - chain의 장점

  1. 코드의 길이가 다르다. 더 간결하다
  2. jquery는 wrapper를 한 번 실행하게 되면 다른 각각의 메소드들은 wrapper를 더 이상 선언/호출하지 않아도 됨. 내부적으로 유지되고 있음. (ex. 하나의 주어가 있다면, 여러 개의 서술어가 연속적으로 꾸며주는 st. 나는 한강에서 친구와 바람을 맞으며 이야기했다)

javascript의 경우, tutorial을 계속 가져와서 사용해야 함

(ex. 나는 한강에 갔다. 나는 친구와 이야기했다. 나는 바람을 맞았다.)

->비효율적

 


  • document.all

: document 밑에 있는 object 모두를 뜻한다.

http://blog.naver.com/PostView.nhn?blogId=graudium&logNo=110025791248


  • bootstrap

: 트위터에서 개발한 UI 라이브러리

bootstrap 공식 홈페이지: https://getbootstrap.com/

부트스트랩 시작하기: https://tworab.tistory.com/71

부트스트랩 버튼 사용하기: https://tworab.tistory.com/72


  • ul li
    목록 만들 수 있는 태그
//아래 코드 실행 시
ddd
- 11
- 22
        <ul>
            ddd
            <li>11</li>
            <li>22</li>
        </ul>
  • 탐색(traversing)의 기능

= chain의 대상을 바꿔서 체인을 계속 연장시킬 수 있는 방법

<html>
    <body>
        <ul class="first">
            <li class="foo"> list item 1 </li>
            <li> list item 2 </li>
            <li class="bar"> list item 3 </li>
        </ul>
        <ul class="second">
            <li class="foo"> list item 1 </li>
            <li> list item 2 </li>
            <li class="bar"> list item 3 </li>
        </ul>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script type="text/javascript">$('ul.first').find('.foo').css('background-color', 'red').end().find('.bar').css('background-color', 'green');</script>
    </body>
</html>

 

코드 설명:

  1. 먼저 ul의 first를 선택
  2. 그 중 .foo를 선택
  3. .foo의 색깔 바꾸기
  4. .end()를 통해 1번으로 다시 돌아가기
  5. 그중. bar를 선택
  6. .bar의 색깔 바꾸기

  • value(.val())

특정 값의 내용 불러오기

ex)

                    else if($("#in_user_pass").val() == ""){
                        alert("비밀번호 입력하세요");
                    }

  • 애니메이션 효과

-jquery의 효과 메소드를 호출하는 것만으로 간단히 효과를 줄 수 있다.

ex)

출처: https://opentutorials.org/course/53/52

<!DOCTYPE html>
<html>
    <head>
        <style>        span {
                color:red;
                cursor:pointer;
            }
            div {
                margin:3px;
                width:80px;
                height:80px;
            }
            div {
                background:#f00;
            }
</style>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <input type="button" id="fadeout" value="fade out" />
        <input type="button" id="fadein" value="fade in" />
        <input type="button" id="hide" value="hide" />
        <input type="button" id="show" value="show" />
        <input type="button" id="slidedown" value="slide down" />
        <input type="button" id="slideup" value="slide up" />
        <input type="button" id="mix" value="mix" />
        <div id="target">
            target
        </div>
        <script>$('input[type="button"]').click( function(e) {
                var $this = $(e.target);
                switch($this.attr('id')) {
                    case 'fadeout':
                        $('#target').fadeOut('slow');
                        break;
                    case 'fadein':
                        $('#target').fadeIn('slow');
                        break;
                    case 'hide':
                        $('#target').hide();
                        break;
                    case 'show':
                        $('#target').show();
                        break;
                    case 'slidedown':
                        $('#target').hide().slideDown('slow');
                        break;
                    case 'slideup':
                        $('#target').slideUp('slow');
                        break;
                    case 'mix':
                        $('#target').fadeOut('slow').fadeIn('slow').delay(1000).slideUp().slideDown('slow', function(){alert('end')});
                        break;
                }
            }) 
        </script>
    </body>
</html>

  • ajax

출처: https://opentutorials.org/course/53/49

 

= Asynchronous JavaScript and XML의 약자

= 자바스크립트를 이용해서 비동기식으로 서버와 통신하는 방식. 이때 XML을 이용한다.

= 꼭 XML을 이용할 필요는 없고, 최근에는 json을 더 많이 이용한다.

= 비동기식이란 여러 가지 일이 동시적으로 발생한다는 뜻으로, 서버와 통신하는 동안 다른 작업을 할 수 있다는 의미.

 

  • $.ajax(settings)

: jQuery를 이용한 ajax통신의 가장 기본적인 API

: 주요 속성 (settings안에 들어가는 property)

 

  • data : 서버에 전송할 데이터, key/value 형식의 객체
  • dataType : 서버가 리턴하는 데이터 타입 (xml, json, script, html)
  • type : 서버로 전송하는 데이터의 타입 (POST, GET)
  • url : 데이터를 전송할 URL
  • success : ajax통신에 성공했을 때 호출될 이벤트 핸들러

 

<!--웹 페이지 쪽 로직-->
<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <div id="result"></div>
        <input type="text" id="msg" />
        <input type="button" value="get result" id="getResult" />
        <script>
            $('#getResult').click( function() {
                $('#result').html('');
                $.ajax({
                    url:'http://opentutorials.org/example/jquery/example.jquery.ajax.php',
                    dataType:'json',
                    type:'POST',
                    data:{'msg':$('#msg').val()},
                    success:function(result){
                        if(result['result']==true){
                          $('#result').html(result['msg']);
                        }
                    }
                });
            })
        </script>
    </body>
</html>



<!-- 예제 1-2. 서버 쪽 로직 -->
<!-- php 코드 -->
<?
echo json_encode(array('result'=>true, 'msg'=>$_REQUEST['msg']));
?>  

Comments