Theme. 답글 입력 구현하기

jQuery를 활용하여 답글을 작성하고, 등록하는 것을 간단하게 구현해보자.

결과부터 확인해보면,

웹 브라우저의 화면에는 다음과 같이 나타난다.

답글 입력 버튼을 누르게 되면, 답글을 남길 수 있도록 입력창이 나타나고, 이를 등록할 수 있는 버튼이 나타난다.

답글을 작성하고, 답글등록 버튼을 누르면 아래에 그 답글 내용이 나타난다.

버튼을 누르면 이어서 다른 input 태그나 버튼이 나타나도록 하기 위해 append() 메서드를 사용하였다.

<div> 태그 안에 append()를 통해 input태그와 버튼을 이어붙인다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<h3>detail view</h3>
<textarea rows="3" cols="50">답글 입력버튼을 통해 답글을 남겨주세요</textarea>
<br><br>
<!-- 답글 입력 버튼 -->
<button type="button" id="answerBtn">답글입력</button>
<br>
 
<div id="answerForm">
<!-- 입력창, 등록버튼 -->
</div> 
 
<p id="demo"></p>
 
<script>
$(document).ready(function() {
    
    $("#answerBtn").click(function () {
        
        let input = "<br>답글:<input type='text' id='answerText'>";
        $("#answerForm").append(input);
        
        let btn = "<br><br><button type='button' id='answer'>답글등록</button>";
        $("#answerForm").append(btn);
        
    });
 
    // 답글등록 버튼은 처음 document가 모두 실행된 이후에 추가된 것이므로 아래와 같이 코드를 작성해줘야 한다. 
    $(document).on("click""#answer"function() {
        let txt = $("#answerText").val();
        $("#demo").text(txt);
    });
 
});
 
</script>
 
</body>
</html>
cs

이때 주의할 것은 답글등록 버튼은 $(document).ready(function() { } 안에서 클릭 이벤트에 대한 코드를 작성하면 실행되지 않는다는 것이다. 왜냐하면, document가 모두 실행되고 난 뒤 새로 추가된 요소이기 때문이다. 따라서 위와 같이 코드를 작성해 주어야 한다.

 

Theme. css(), attr()

css()를 통해 디자인의 변경을 하거나 attr()를 통해 속성을 추가할 수 있다.

먼저, 테이블을 만들고, mouseover, mouseout을 할 때, tr 태그 중 class가 "hover"인 tr에 대해서만 css()를 이용해 배경색이 바뀌도록 하면,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
 
</head>
<body>
 
<table border="1">
<col width="50"><col width="200"><col width="150">
 
<tr>
    <th>번호</th><th>이름</th><th>나이</th>
</tr>
<tr class="hover">
    <th>1</th><td>홍길동</td><td>24</td>
</tr>
<tr class="hover">
    <th>2</th><td>성춘향</td><td>16</td>
</tr>
<tr>
    <th>3</th><td>일지매</td><td>22</td>
</tr>
</table>
 
<p>p 태그입니다.</p>
 
<button type="button">버튼</button>
 
<script>
$(document).ready(function(){
 
    $("tr.hover").mouseover(function(){
        $(this).css('background''#00ff00');
    });
    $("tr.hover").mouseout(function(){
        $(this).css('background''#ffffff');
    });
 
});
 
 
</script>
</body>
</html>
cs

마우스를 올려놓았을 때

 

뗐을&nbsp; 때

이는 td 태그에 대해서만 적용할 수도 있다.

마우스를 올려놓았을 때

 

뗐을 때

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
$(document).ready(function(){
 
    // $("tr.hover").mouseover(function(){
    //     $(this).css('background', '#00ff00');
    // });
    // $("tr.hover").mouseout(function(){
    //     $(this).css('background', '#ffffff');
    // });
 
    $("td").mouseover(function(){
        $(this).css('background', '#00ff00');
    });
    $("td").mouseout(function(){
        $(this).css('background', '#ffffff');
    });
 
});
 
</script>
cs

이제 버튼을 클릭했을 때, p 태그의 배경색, 글자색을 바꿔보자.

버튼을 누르게 되면,

1
2
3
4
5
6
7
$('button').click(function(){
        
        $('p').css('background', '#0000ff');
        $('p').css('color', '#ffffff');
        // 아래와 같이 한번에 작성할 수 있다.
        $('p').css({'background':'#00ff00', 'color':'#ffffff'});
    });
cs

또한, 버튼 클릭 시 p 태그에 id와 class를 추가할 수 있는데, 

$('p').attr('id', 'pid');
$('p').attr('class', 'mycss');

의 형식으로 추가하면 된다.

이 경우 <style> 태그 안에서 css 문법을 통해 p 태그를 클릭하는 등에 대한 이벤트 발생시 효과를 줄 수 있을 것이다.

예를 들면,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
 
<style>
.mycss{
    background-color: #ff0000;
    color: #ffff00;
    border: 1px solid;
}
 
</style>
</head>
<body>
 
<table border="1">
<col width="50"><col width="200"><col width="150">
 
<tr>
    <th>번호</th><th>이름</th><th>나이</th>
</tr>
<tr class="hover">
    <th>1</th><td>홍길동</td><td>24</td>
</tr>
<tr class="hover">
    <th>2</th><td>성춘향</td><td>16</td>
</tr>
<tr>
    <th>3</th><td>일지매</td><td>22</td>
</tr>
</table>
 
<p>p 태그입니다.</p>
 
<button type="button">버튼</button>
 
<script>
$(document).ready(function(){
 
    $('button').click(function(){
        
        $('p').attr('id''pid');
    
        $('p').attr('class''mycss');
    });
 
    $(document).on('click''#pid'function (){
        alert('pid click');
 
        let id = $('p').attr('id');
        alert(id);
    });
        
 
});
 
 
</script>
</body>
</html>
cs

 

Theme. id, class, name에 대한 jquery 작성 형식

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p>Hello Jquery</p>
 
<p id="id">Hello Jquery</p>
 
<p class="cls">Hello Jquery</p>
 
<p name="name1">Hello Jquery</p>
 
<button  type="button">button</button>
 
<script>
 
$(document).ready(function(){
 
  $('button').click(function(){
    // $('p').hide(); - p 태그에 대해 적용
    // $('*').hide(); - 모든 것들에 대해 적용
    // $('p#id').hide(); - p 태그 중 id가 "id"인 태그에 대해 적용
    // $('p.cls').hide(); - p 태그 중 class가 "cls"인 태그에 대해 적용  
    $('p[name=name1]').hide(); // p 태그 중 name이 "name1"인 태그에 대해 적용
  });
 
})
 
 
</script>
 
</body>
</html>
cs

 

Theme. 입력 데이터의 전송

입력 데이터의 전송 방법에는

1. <a> 태그의 이용(<a href = "">)

2. <form> 태그의 이용(<form action="")

3. location.href=""

 

사용 예시는 아래 코드를 참고한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<!-- 입력 데이터 전송 
 
  <a href=""
 
  <form action=""
 
  location.href=""
 
-->
<a href="NewFile.jsp">NewFile로 이동</a>
<br><br>
 
이름:<input type="text" id="name"><br>
나이:<input type="text" id="age"><br>
주소:<input type="text" id="address"><br>
<button type="button" id="send">버튼</button>
 
<script>
$(document).ready(function(){
    $('#send').click(function() {        
      let name = $('#name').val();
      let age = $('#age').val();
      let address = $('#address').val();
    
      location.href = "NewFile.jsp?name=" + name + "&age=" + age + "&address=" + address;
    });
});
 
</script>
 
<br><br><br>
 
<form id="frm">
  이름:<input type="text" name="name"><br>
  나이:<input type="text" name="age"><br>
  주소:<input type="text" name="address"><br>
  
  <button type="button" id="btn">전송</button>
</form>
 
<script>
$(document).ready(function(){
 
  $('#btn').click(function(){
 
    $("#frm").attr("action""NewFile.jsp").submit();
    
  });
});
 
 
</script>
</body>
</html>
cs

NewFile.jsp는 

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
    String address = request.getParameter("address");
    
    System.out.println("이름:" + name);
    System.out.println("나이:" + age);
    System.out.println("주소:" + address);
%>
cs

 

Theme. 태그를 새로 추가하는 방법

1. 문자열로 추가

2. JS로 추가

3. jQuery로 추가

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<div id="demo">
</div>
<br>
<button type="button">버튼</button>
 
<script type="text/javascript">
$(document).ready(function(){
    
    $("button").click(function(){
        
        // 문자열로 추가
        let str = "<p id='pid'>p 태그를 추가합니다</p>";
        $("#demo").append(str);
        
        // JavaScript로 추가
        let jsStr = document.createElement("h3");
        jsStr.setAttribute("id""h3id");
        jsStr.innerHTML = "h3 태그를 추가합니다.";
        $("#demo").append(jsStr);
        
        // Jquery 추가
//         let jqStr = $("<span></span>").text("span 태그를 추가합니다.");
        let jqStr = $("<span>").text("span 태그를 추가합니다.");
        jqStr.attr("id""spanid");
        $("#demo").append(jqStr);
        
    });
});
 
 
 
</script>
 
</body>
</html>
cs

 

그 결과 버튼을 누르면

Theme. radio, checkbox, select, table의 사용

1.radio

input 태그의 type 중 하나인 radio의 경우 id는 사용할 수 없고, name을 사용해야 한다.

버튼을 누르면,

체크한 항목을 저장하고, 기본적으로 특정 항목이 선택되도록 하는 예시를 살펴보자.

사과를 선택하고 버튼을 클릭했고, 이후 기본적으로 배가 선택된 모습을 확인할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<!--  radio  -->
<!--  type이 radio이므로 id는 사용할 수 없고 name을 사용해야 한다-->
<ul>
    <li><input type="radio" name="radioTest" value="사과">사과</li> 
    <li><input type="radio" name="radioTest" value="배"></li>
    <li><input type="radio" name="radioTest" value="바나나">바나나</li>
</ul>
 
<button type="button" id="btn">선택</button>
 
<script>
$(document).ready(function(){
    $("#btn").click(function(){
        // getter
    // 체크된 항목이 radioVal에 저장
        let radioVal = $("input[name='radioTest']:checked").val();
        alert(radioVal);
 
        // setter([] 안에 값을 적어줘야 한다.)
        $("input[name='radioTest']").val(["배"]); // 버튼 누르면 기본적으로 배가 선택되도록 함
 
    });
});
 
</script>
 
</body>
</html>
cs

2. checkbox

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<!--  checkbox -->
 
<input type="checkbox" id="ch1" name="ch">그림 그리기
<input type="checkbox" id="ch2" name="ch">음악 듣기
<br><br>
<button type="button" id="cbtn">체크</button>
 
<script type="text/javascript">
$(document).ready(function(){
    
    $("#cbtn").click(function(){
        // getter
        let check1 = $("#ch1").is(":checked"); // #ch1이 선택되면 true, 선택되지 않으면 false 반환
        alert(check1);
 
        let check2 = $("input:checkbox[id='ch2']").is(":checked"); // #ch2이 선택되면 true, 선택되지 않으면 false 반환
        alert(check2);
        
        // setter
    // id가 ch1인 박스가 기본적으로 선택되도록
        $("#ch1").attr("checked""checked"); // attribute
        $("#ch1").prop("checked"true); // property
    
    });
    
    
});
 
</script>
 
</body>
</html>
cs

3. select

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<!-- select -->
 
<select id="food">
    <!-- prepend 시 추가 되는 곳 -->
    <option value="햄버거">햄버거</option>
    <option value="피자" selected="selected">피자</option>
    <option value="치킨">치킨</option>
    <!-- append 시 추가 되는 곳 -->
</select>
 
<p id="demo">선택한 음식이 추가되는 공간</p>
 
<button type="button" id="sbtn">선택</button>
<button type="button" id="append">추가(뒤에)</button>
<button type="button" id="prepend">추가(앞에)</button>
 
<script type="text/javascript">
// onchange
$("#food").change(function(){
    let val = $(this).val();
    $("#demo").html(val); // p 태그의 텍스트 변화
});
// 선택된 항목을 알려줌
$("#sbtn").click(function(){
    alert($("#food").val());
});
 
$("#append").click(function(){ 
    
    $("#food").append("<option value='스테이크'>스테이크</option>"); // 기존 옵션 맨 마지막 뒤에 옵션 추가
});
 
$("#prepend").click(function(){
    
    $("#food").prepend("<option value='떡볶이'>떡볶이</option>"); // 기존 옵션 첫번째 앞에 옵션 추가
});
 
 
</script>
 
</body>
</html>
cs

이를 실행해보자.

처음엔 피자가 선택되어 있을 것이다(selected 이용)

햄버거를 선택해보면,

선택 버튼을 누르면,

추가(뒤에) 버튼을 누르고 select 태그의 항목들을 확인해보면,

추가(앞에) 버튼을 누르고 확인해보면,

4.  table에 append 활용

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<table border="1" id="table">
<col width="50"><col width="200"><col width="100">
<tr>
    <th>번호</th>
    <th>제목</th>
    <th>작성</th>
</tr>
 
<!-- 아래 append를 이용하면 다음과 같이 생성된다.
<tr>
    <th>1</th>
    <th>오늘은 금요일 입니다</th>
    <th>Tom</th>
</tr> 
-->
 
</table>
 
<script type="text/javascript">
 
$("#table").append(
            $("<tr>").append(
                    $("<th>").append(1),
                    $("<td>").append("오늘은 금요일 입니다"),
                    $("<td>").append("Tom")
                    )
            );
 
 
</script>
 
</body>
</html>
cs

'JavaScript > jQuery' 카테고리의 다른 글

jQuery 기본(1)  (2) 2023.02.02

Theme. 제이쿼리(jQuery)란?

 

제이쿼리는 자바스크립트 언어를 간편하게 사용할 수 있도록 단순화시킨 오픈 소스 기반의 자바스크립트 라이브러리이다.

제이쿼리를 이용하면 문서 객체 모델(DOM)과 이벤트에 관한 처리를 손쉽게 구현할 수 있다.

또한, Ajax 응용 프로그램 및 플러그인도 제이쿼리를 활용하여 빠르게 개발할 수 있다.

 

Theme. jQuery의 적용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<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">
  <title>Document</title>
 
<!-- jQuery 적용 3가지 방법 -->
<!-- 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
-->
 
<!-- <script type="text/javascript" src="./jquery.min.js"></script> -->
 
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
 
</head>
<body>
  
</body>
</html>
cs

위와 같이 <head> 태그 내에 <script> 태그를 삽입하면 된다. 아래 파일을 저장해서 사용해서 쓸 수 있고,

jquery.min.js
0.09MB

https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js

https://code.jquery.com/jquery-3.6.3.min.js

를 src의 값으로 지정하여 사용할 수 있다.

 

Theme. jQuery 문법

간단하게 나타내면, $(선택자).동작함수(); 로 표현할 수 있다.여기서 $는 제이쿼리를 의미하고, 제이쿼리에 접근할 수 있게 해주는 식별자이다.위 기본 문법을 다시 적어보면,

$(태그 또는 id 또는 class 또는 name).이벤트함수(매개변수);

로 표현할 수 있다.

$() 함수를 통해 생성된 요소는 제이쿼리 객체(jQuery object)라고 한다.

 

Theme. Document 객체의 ready() 메서드

먼저 문법을 살펴보면,

1
2
3
4
5
$(document).ready(function() {
 
    제이쿼리 코드;
 
});
cs

로 표현할 수 있다. 이는 jQuery 코드가 웹 브라우저가 문서 내 모든 요소를 로드한 뒤에 실행될 수 있도록 한다. 

이는,

1
2
3
4
5
$(function() {
 
    제이쿼리 코드;
 
});
cs

 

위와 같이 표현할 수 있다. 

 

Theme. getter 와 setter 메서드

선택자에 의해 선택된 요소의 값을 읽거나 설정하기 위해서는 제이쿼리 메소드를 통해 해당 요소에 접근해야만 한다.

getter 메소드는 선택된 요소에 접근하여 그 값을 읽어오기 위한 메소드이다.

이러한 getter 메소드는 아무런 인수를 전달하지 않고 호출한다.

예를 들면, $("h1").html();

 

setter 메소드는 선택된 요소에 접근하여 그 값을 설정하기 위한 메소드이다.

이러한 setter 메소드는 대입하고자 하는 값을 인수로 전달하여 호출한다.

예를 들면, $("h1").html("새로운 값");

 

예제를 통해 효과를 확인해보자

기본 모습은 다음과 같다.

1
2
3
4
5
6
7
8
9
<body>
 
  <p>서울 일반고 입시 절대평가로…석차백분율제 폐지</p>
 
  <p id="demo">A∼E 학점 각각 환산하지 않고 최하위등급 과목수만 평가</p>
  
  <p class="cls">서울 일반계 고등학교의 입시 전형에 남아있던 상대평가 환산 방법이 절대평가로 바뀔 예정이다.</p>
  
  <h3 class="cls">새 전형 방식은 올해 3월 중학교 2학년이 되는 학생들부터 적용된다.</h3>
cs

 

이제 getter와 setter를 적용해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html lang="en">
<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">
  <title>Document</title>
 
<!-- jQuery 적용 3가지 방법 -->
<!-- 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
-->
 
<!-- <script type="text/javascript" src="./jquery.min.js"></script> -->
 
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
 
</head>
<body>
 
  <p>서울 일반고 입시 절대평가로…석차백분율제 폐지</p>
 
  <p id="demo">A∼E 학점 각각 환산하지 않고 최하위등급 과목수만 평가</p>
  
  <p class="cls">서울 일반계 고등학교의 입시 전형에 남아있던 상대평가 환산 방법이 절대평가로 바뀔 예정이다.</p>
  
  <h3 class="cls">새 전형 방식은 올해 3월 중학교 2학년이 되는 학생들부터 적용된다.</h3>
  
<script>
 
$(document).ready(function () {
  
  // setter
  $("p").html("새로운 문자열"); // JS의 innerHTML과 같은 효과
 
});
 
</script>
 
</body>
</html>
cs

이는, <p> 요소에 html() 메서드를 "새로운 문자열"이라는 텍스트를 설정하는 setter 메서드이다. 

마치, document.getElementById("p").innerHTML = "새로운 문자열"; 과 같다.

(또는,  HTML로 해석될 텍스트가 존재하지 않으므로 document.getElementById("p").innerText = "새로운 문자열"; 으로 작성해도 된다.)

추가로, 아래와 같이 설정하는 텍스트를 HTML태그로 감싸서 효과를 줄 수도 있다.

 

1
2
3
4
5
6
7
8
9
10
<script>
 
$(document).ready(function () {
  
  // setter
  $("p").html("<strong>새로운 문자열</strong>");
 
});
 
</script>
cs

 

1
2
3
4
5
6
7
8
9
10
11
<script>
  
$(document).ready(function () {
  // setter
  let arrPtag = document.getElementsByTagName("p");
    for (i = 0; i < arrPtag.length; i++) {
        arrPtag[i].innerHTML = "<strong>새로운 문자열</strong>"
    }
});
 
</script>
cs

 

jQuery를 사용하지 않으면, 동일한 효과를 주기위해 위와 같이 코드가 좀 더 길어짐을 알 수 있다. 

즉, jQuery가  JavaScript의 경량화, 간략화의 기능을 하고 있다.

 

getter의 경우, 아래와 같이 인수를 전달하지 않고 호출한다. html() 부분!

1
2
3
4
5
6
7
8
9
10
<script>
 
$(document).ready(function () {
  // getter
  // id 선택자를 이용
  let txt = $("#demo").html();
  alert(txt);
});
 
</script>
cs

이 또한, jQuery를 사용하지 않으면, 아래와 같이 작성할 수 있다.

1
2
3
4
5
6
7
8
9
<script>
 
$(document).ready(function () {
  // getter
  let txt = document.getElementById("demo").innerHTML;
  alert(txt);
});
 
</script>
cs

 

Theme. 이벤트 처리

사용자는 마우스를 움직이거나, 요소를 클릭하거나, 텍스트 박스에 글을 쓰는 등 수많은 종류의 동작(action)을 수행하는데, 이러한 동작들은 모두 이벤트(event)를 발생시킨다.

웹 페이지에서는 수많은 이벤트가 계속해서 발생한다.

특정 요소에서 발생하는 이벤트를 처리하기 위해서 이벤트 핸들러(event handler)라는 함수를 작성한다.

이벤트 핸들러가 연결된 특정 요소에서 지정된 타입의 이벤트가 발생하면, 웹 브라우저는 연결된 이벤트 핸들러를 실행하게 된다.

이벤트 핸들러 함수는 이벤트 객체(event object)를 인수로 전달받을 수 있고,

이렇게 전달받은 이벤트 객체를 이용하여 이벤트의 성질을 결정하거나, 이벤트의 기본 동작을 막을 수도 있다.

 

예제를 통해 살펴보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
 
</head>
<body>
 
<p id="demo">버튼을 클릭해주세요</p>
 
<button type="button" id="btn">버튼</button>
 
<script>
$(function() {
 
  // id가 "btn"인 요소에 클릭(click)이벤트 핸들러 연결하고 "button click"이라는 창이 뜨도록 한다.
  $("#btn").click(function(){
        alert('button click');
    });
 
  // button 요소를 클릭하면, "button click"이라는 창이 뜨도록 한다(1)
  $("button").click(function(){
        alert('button click');
    });
  // button 요소를 클릭하면, "button click"이라는 창이 뜨도록 한다(2)
  $("button").on("click"function() {
        alert('button click');
    });
// button 요소를 클릭하면, "button click"이라는 창이 뜨도록 한다(3) (아래 함수 참고)
  $("button").on("click, btnFunc");
 
});
 
function btnFunc() {
  alert("button click");
}
 
</script>
 
</body>
</html>
cs

 

getter와 setter 메서드와 click이벤트를 만들어보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
입력: <input type="text" id="text">
<br><br>
<input type="button" id="btn" value="할 수 있는가?">
 
<script type="text/javascript">
 
$("#btn").click(function() {
    
  // setter
    $("#text").val("나는 할 수 있다");
 
    // getter
    let text = $("#text").val(); // javascript에서의 .value와 동일
  alert(text);
    
});
 
</script>
 
</body>
</html>
cs

 

다음 예제에서 요소를 click 했을 때 다양한 효과가 나타나도록 해보자.

주석 처리를 해가면서 하나씩 실행해보도록 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p>최하위등급 과목수만 평가</p>
 
<div>
    <p>서울 일반고 입시 절대평가로…석차백분율제 폐지</p>
    
    <p id="demo">A∼E 학점 각각 환산하지 않고 최하위등급 과목수만 평가</p>
    
    <p class="cls">서울 일반계 고등학교의 입시 전형에 남아있던 상대평가 환산 방법이 절대평가로 바뀔 예정이다.</p>
    
    <h3 class="cls">새 전형 방식은 올해 3월 중학교 2학년이 되는 학생들부터 적용된다.</h3>
</div>
 
<script type="text/javascript">
$(document).ready(function() {
    
    $("p").click(function () {
        alert("p tag click");
    });
    
    // div 태그 안에 있는 p 태그를 클릭할 때만 반응하도록
    $("div p").click(function () {
        alert("p tag click");
    });
    
    // div 태그 안에 있는 class명이 cls인 것들을 클릭할 때만 반응하도록
    $("div .cls").click(function () {
        alert("p tag click");
    });
    
    // div 태그 안에 있는 p 태그 중 class명이 cls인 것들을 클릭할 때만 반응하도록
    $("div p.cls").click(function () {
        alert("p tag click");
    });
    
    // click한 p 태그의 배경색 바꾸기
    $("p").click(function () {
        $(this).css("background""#ff0000");
    });
    
    // click한 p 태그 숨기기
    $("p").click(function () {
        $(this).hide();
    });
    
    // h3 태그 click하면, p 태그가 전부 보이도록
    $("h3").click(function () {
        $("p").show();
    });
    
});
 
</script>
 
 
</body>
</html>
cs

 

'JavaScript > jQuery' 카테고리의 다른 글

jQuery 기본(2)  (0) 2023.02.05

+ Recent posts