본문 바로가기
학원수업/2월

02/08 jQuery

by 코딩마스터^^ 2023. 2. 8.

JSON.parse()

JSON.parse() 메서드는 JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성합니다. 선택적으로, reviver 함수를 인수로 전달할 경우, 결과를 반환하기 전에 변형할 수 있습니다.

submit이슈

<a href="javascript:함수()"></a>
이 경우는 submit에 대한 이슈가 없음

<input type="button" value ="전송"> 이 경우도 submit에 대한 이슈가 없음

<button>전송</button> submit이슈가 있음-주의할것
반드시  event.preventDefault()를 호출하여 이벤트 버블링 방어할것

 

문제상황

페이지 새로고침이 발생함
화면이 하얗게 변했어요
화면이 계속 렌더링되고 있어요-F5-새로고침

기본 동작 막기

브러우저의 기본 태그들은 기본 이벤트를 갖고 있는 경우가 많습니다. 예로 <a>태그는 클릭시 해당 URL로 이동하고 <form>은 submit시 서버에 폼이 전달돼 새로고침이 됩니다.

이러한 기본 브라우저의 이벤트를 방지하기 위한 방법이 있습니다.

  1. event.preventDefault()
  2. return false

위의 두 가지 방법도 다른 상황에서만 적용 가능하다.

1. event.preventDefault()

콜백함수에 event.preventDefault()을 사용하면 브라우저의 기본 동작을 막을 수 있다. event.preventDefault()을 통해서 기본동작을 멈춘 상태에서 event.defaultPrevented의 값은 true된다. 이것을 이용해서 추가적인 조건도 걸어줄 수있다.

2. return false

return false는 onclick과 같은 on[event]로 이벤트를 걸어준 경우에만 사용할 수 있다. document.onclick=콜백함수 와 같이 작성된 경우 return false 해주면 기본 동작을 멈출 수 있다. 하지만 html 태그에서 on[event]속성을 이용해 이벤트를 생성해 준다면, 콜백함수에 return false로 동작이 멈추질 않는다.

 

출처 : https://velog.io/@proshy/JS-%EB%B8%8C%EB%9D%BC%EC%9A%B0%EC%A0%80-%EA%B8%B0%EB%B3%B8-%EC%9D%B4%EB%B2%A4%ED%8A%B8%EC%99%80-%EB%B2%84%EB%B8%94%EB%A7%81-%EB%B0%A9%EC%A7%80

 

[JS] 브라우저 기본 이벤트와 버블링,캡쳐링 방지

브라우저의 기본 이벤트 혹은 버블링의 현상을 방지하고 싶은 상황이 있습니다. 이를 방지하기 위한 방법도 여러가지 입니다.다만, 상황에 맞는 방법을 사용해야지 추후에 다른 문제점이 발생

velog.io

 jQuery

 jQuery는 HTML의 DOM 조작과 이벤트 제어, 애니메이션 그리고 Ajax까지 웹 화면을 다루는 자바스크립트 라이브러리입니다. 

 

 

https://www.jeasyui.com/demo/main/index.php

 

Live Demo - jQuery EasyUI

 

www.jeasyui.com

요즘은 잘 안쓰지만 공부하기는 좋다!!

자바스크립트코드를 UI나 이벤트 처리 적용해서 공부할때 쓰기

block요소는 빈칸을 다 여백으로 채운다

이런 처리를 하는것이 리액트이다.

얘가 하는 일이 리액트가 만들어준다.

안보이는곳에서...

datagrid로 표 만들어 주기

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Basic DataGrid - jQuery EasyUI Demo</title>
    <link
      rel="stylesheet"
      type="text/css"
      href="../themes/default/easyui.css"
    />
    <link rel="stylesheet" type="text/css" href="../themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="../demo/demo.css" />
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <script type="text/javascript" src="../js/jquery.easyui.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      //ready함수의 파라미터로 함수를 전달할수있다.
      $(document).ready(function () {
        console.log("DOM Tree 그려졌을때");
      });
    </script>

    <h2>부서관리시스템</h2>
    <div style="margin: 20px 0"></div>

    <table
      class="easyui-datagrid"
      title="Basic DataGrid"
      style="width: 700px; height: 250px"
      toolbar="#toolbar"
      data-options="singleSelect:true,collapsible:true,url:'dept.json',method:'get'"
    >
      <thead>
        <tr>
          <th data-options="field:'deptno',width:100">부서번호</th>
          <th data-options="field:'dname',width:150">부서명</th>
          <th data-options="field:'locㅋ',width:150,align:'center'">지역</th>
        </tr>
      </thead>
    </table>
    <div id="toolbar">
      <a
        href="javascript:void(0)"
        class="easyui-linkbutton"
        iconCls="icon-add"
        plain="true"
        onclick="newUser()"
        >New User</a
      >
      <a
        href="javascript:void(0)"
        class="easyui-linkbutton"
        iconCls="icon-edit"
        plain="true"
        onclick="editUser()"
        >Edit User</a
      >
      <a
        href="javascript:void(0)"
        class="easyui-linkbutton"
        iconCls="icon-remove"
        plain="true"
        onclick="destroyUser()"
        >Remove User</a
      >
    </div>
  </body>
</html>

jQuery문 기호는 $

 

- DOM과 관련된 처리를 쉽게 구현 할 수 있다.

- 규칙성을 가지고 이벤트를 처리 할 수 있다.

- 애니메이션 효과를 쉽게 만들 수 있다.

- AJAX 처리 방식을 편리하게 사용 할 수 있다.

 

 그 밖에도 jQuery는 작은 양의 코드로도 많은 일을 할 수 있게 설계되어 있어 프로그래머가 아니어도 꽤 이해하기가 쉬운 구문을 가지고 있습니다. Javascript와 jQuery의 차이점을 보기 위해 예시를 작성해보았습니다.

Javascript

var titleElements = document.getElementsByClassName("title"); 

for (var titleElement in titleElements) {
   titleElement.className = titleElement.className + " selected"; 
}

jQuery

$(".title").addClass("selected");

 이와 같이 jQuery는 작은 양의 코드로 Javascript로 작성된 많은 양의 코드와 동일한 동작을 할 수 있습니다.

https://7942yongdae.tistory.com/13

 

jQuery - 제이쿼리란?

시작하기 jQuery는 HTML의 DOM 조작과 이벤트 제어, 애니메이션 그리고 Ajax까지 웹 화면을 다루는 자바스크립트 라이브러리입니다. 지금은 Angular, React, Vue 같은 화면을 다루는 여러 가지 기술들이 있

7942yongdae.tistory.com

 

이벤트 처리

제이쿼리에서는 bind사용한다.

 

ajax가 url에 연결 그곳의 값을 파라미터자리에 넣어준다.

//파라미터 데이터에는 boardSellAction.html의 값을 자동으로 받아줌

responseText와 같은 기능 그러나 더 간단한 형식

 

제이쿼리는 이제는 표준이라고는 할수없다.

체험이라고 생각하기^^

jQuery는 화면과 관련된 프레임워크나 라이브러리가 발전함에 따라 이전보다 인기를 끌지 못하고 있는 것은 사실입니다. 그럼에도 현대화하지 않은 프로젝트나 간단하게 화면을 구성해서 사용하는 소규모 프로젝트에서는 여전히 좋은 자바스크립트 라이브러리입니다.

 

제이쿼리는 라이브러리이다

jquery.min.js-들여쓰기나 여백완전제거 사이즈 줄임

jquery.js

 

html, css, js

서버PC에 물리적인 위치를 갖는다.

실행은 로컬 pc에서 실행된다.

다운로드 된다.

서버에서 각 각 로컬 피씨에 

로컬 피씨에는 OS가 있다.

OS에는 브라우저가 설치되어있다.

요즘 브라우저는 V8엔진을 쓴다.

그래서 node.js탄생...ㅎ

 

브라우저는 다운로드 된 파일을 샐행하는것

동기화가 안된다.

클라이언트 사이드 렌더링

정적 페이지

이미 결정됨

유동적이지 않음

이미 서버에서 나와있다.

다운로드 파일의 크기가 크면 속도가 오래 걸린다.

줄이려면 들여쓰기 여백 공백문자 없애야한다.->jquery.min.js

 

제이쿼리는 표준이 아니다.

상속과 확장이 있다.

오염된것이다.

오염이 되면 다른 이종간의 연계가 어렵다.

 

$를 사용한다.-Express Language

`` 빽틱기호

`${ }`

 

$(아이디|클래스|태그명|document).ready

document->XXX.html을 가리킨다.

 

document.write( )

브라우저에 쓴다.

 

<div id = "d_msg">요기에...</div>

d_msg.innerText==>d_msg.text('<h3>값</h3>')

태그는 브라우저가 해석해준다.  V8엔진이 해석을 한다.

 

데이터를 서버에서 결정한다.

html은 오라클 서버랑 연동이 되나요? 당연 아니;;

서버와 화면사이의 물리적인 거리가있다.

JSP(Java Server Page)

서버사이드 렌더링이다.

서버가 결정한다. 이미 결정이 된것을 html이 못바꾼다. 동기화 안된다.

 

XXX.jsp라고 쓰고 XXX.html이라고 읽는다.

mime type

image/jpg

image/gif

video/mp4

video/avi

text/javascript

text/css

text/html

application/msword

application/json

 

mime type으로 결정된다.

너 누긔야...?

xxx.java ->xxx.class -> print("<h3></h3>")

 

웹+앱=하이브리드 앱

서로 이종간에 만나는 부분-interface-결합도 낮춤, 통합가능하게, 재사용성 높임

유지보수 편해짐 

 

js-html

js-js

html-js

html-jquery-js

자유자재로 되어야한다.

 

API - Pure코드 잘 다루어야... 표준적인 코드를 잘 알고 나서 멋을 부려야...

 

GET방식은 브라우저가 인터셉트 당한다.

POST는 무조건 전달해준다. 포장해서 준다. 뭐가 들어있는지 모른다.

 

GET

쿼리스트링으로 전달된다.-입력값이

링크를 걸 수 있다.

header에 저장된다.

전달할 수 있는 값에 제한이 있다.

브라우저로부터 인터셉트 당한다.-304->200

자꾸 같은걸 요청하면 서버한테 말안하고 브라우저가 알아서 함^^

 

POST

body에 저장된다.

보이지 않는다.

링크 못건다.

값에 제한이 없다.

단위테스트 불가능하다.-자바스크립트가 있어야..

포장되어있어 인터셉트 안당한다.

 

사진 보이기

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <link rel="stylesheet" href="./picture.css" />
    <title>Document</title>
    <script>
      const startMethod = (td) => {
        // 마우스 오버된 사진의 id값 가져오기
        const pic = $(td).attr("id");
        console.log(pic);
        location.href =
          "pictureDetail.html?id=" + pic + "&timestamp=" + new Date().getTime();
      };
      const clearMethod = () => {
        // console.log("clearMethod");
        $("#d_pic").html("");
      };
    </script>
  </head>
  <body>
    <div id="d_pic"></div>
    <table border="1">
      <thead>
        <th colspan="2">그림 목록</th>
      </thead>
      <tbody>
        <tr>
          <td align="center">
            <img src="../../images/sample/회의.jpg" width="50" height="50" />
          </td>
          <td id="0" onmouseover="startMethod(this)" onmouseout="clearMethod()">
            사진1
          </td>
        </tr>
        <tr>
          <td align="center">
            <img src="../../images/sample/회의-1.jpg" width="50" height="50" />
          </td>
          <td id="1" onmouseover="startMethod(this)" onmouseout="clearMethod()">
            사진2
          </td>
        </tr>
        <tr>
          <td align="center">
            <img src="../../images/sample/회의-2.jpg" width="50" height="50" />
          </td>
          <td id="2" onmouseover="startMethod(this)" onmouseout="clearMethod()">
            사진3
          </td>
        </tr>
        <tr>
          <td align="center">
            <img src="../../images/sample/회의-3.jpg" width="50" height="50" />
          </td>
          <td id="3" onmouseover="startMethod(this)" onmouseout="clearMethod()">
            사진4
          </td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
  $(document).ready(function () {
    const queryString = new URLSearchParams(window.location.search); //아작스 내부 통신이용해서 처리중
    const id = queryString.get("id");
    console.log(id);
    let img = null;
    const pics = ["회의.jpg", "회의-1.jpg", "회의-2.jpg", "회의-3.jpg"];
    for (let i = 0; i < pics.length; i++) {
      console.log(id + "," + i);
      if (id == i) {
        img = pics[i];
        console.log(img);
        $("#imgDetail").attr("scr", "../../images/sample/" + img);
      } //end of if
    } //end of for
  });
</script>
<img
  id="imgDetail"
  src="../../images/sample/회의-2.jpg"
  width="400px"
  height="400px"
  alt="그림"
/>
div#d_pic {
  position: absolute;
  top: 200px;
  left: 200px;
}

JSP로 하는것은 이클립스로 하기!

인텔리제이로 하지마세요.

복잡함.

html안에 자바넣기

jsp 

html과 java를 섞어서 쓰려고 하는것이다.

'학원수업 > 2월' 카테고리의 다른 글

02/09 자바스크립트 JSP React  (0) 2023.02.09
Youtube API 사용하기  (0) 2023.02.09
02/07 48회차 Ajax, 비동기 통신  (0) 2023.02.07
02/07 48회차 Google API사용하기  (0) 2023.02.07
02/03 47회차 수업  (0) 2023.02.03

댓글