Theme. load()

load() 메소드는 선택한 요소에서 호출하는 제이쿼리 Ajax 메소드이다.

load() 메소드는 서버에서 데이터를 읽은 후, 읽어 들인 HTML 코드를 선택한 요소에 배치한다.

또한, 선택자를 URL 주소와 함께 전송하면, 읽어 들인 HTML 코드 중에서 선택자와 일치하는 요소만을 배치한다.

 

예제를 통해 살펴보자.

data1.jsp 파일은 다음과 같다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    
    <p id="data1">사과</p>
 
    
    <h3 id="data2">바나나</h3>
</body>
</html>
cs

이를 index1.jsp 파일에서 load() 메서드를 활용해서 선택한 요소에 배치해본다.

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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">button</button>
 
<script type="text/javascript">
$(document).ready(function(){
    
    $("button").click(function(){
        
        // id가 demo인 요소 안에 "data1.jsp"의 데이터를 배치한다.
        $("#demo").load("data1.jsp"); 
        
        // id가 demo인 요소 안에 데이터 중 선택자가 #fruit1인 데이터만 배치한다.
        $("#demo").load("data1.jsp #fruit1"); 
 
    });
});
 
</script>
 
</body>
</html>
cs

이번엔 파라미터를 가져와 배치하는 예제이다.

data2.jsp 파일은 다음과 같다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
txt1=<%=request.getParameter("txt1"%>
<br>
txt2=<%=request.getParameter("txt2"%>
 
</body>
</html>
cs

index2.jsp 파일은 다음과 같다.

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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">button</button>
 
<script type="text/javascript">
$(document).ready(function(){
    
    $("button").click(function(){
        
        // txt1, txt2를 파라미터로 설정하고 load
        $("#demo").load("data2.jsp""txt1=abc&txt2=가나다"); 
        $("#demo").load("data2.jsp", {txt1:"ABC", txt2:"라마바"}); //json 방식으로도 사용가능
 
    });
});
 
</script>
 
</body>
</html>
cs

그 결과 버튼을 누르면,

다음은 callback함수를 이용하여 load() 메서드를 사용하는 예제이다.

위와 동일하게 data2.jsp파일을 이용하고,

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<button type="button">button</button>
 
<script type="text/javascript">
$(function(){
    
    $("button").click(function(){
        
        $("#demo").load(
                "data2.jsp"// 접근할 파일
                {txt1:"ABC", txt2:"라마바"}, // 넘겨받을 매개변수
                function name(data, status, xhr){ 
                    $('#demo').append('<p>'+data+'</p><br>');
                    $('#demo').append('<p>status='+status+'</p><br>');
                    $('#demo').append('<p>xhr='+xhr+'</p><br>');
                    $('#demo').append('<p>xhr.status='+xhr.status+'</p><br>');
                    $('#demo').append('<p>xhr.statusText='+xhr.statusText+'</p><br>');
                }
            );
 
    });
});
 
</script>
 
</body>
</html>
cs

이때, 

data: 데이터를 저장하는 객체

status: 상태를 갖고 있는 객체. 성공하면 'success' 반환, 에러가 발생하면, 'error' 반환

xhr: XMLHttpRequest 객체

 

Theme. $.ajax()

$.ajax() 메서드는 모든 제이쿼리 Ajax 메소드의 핵심이 되는 메서드이다.

$.ajax() 메서드는 HTTP 요청을 만드는 강력하고도 직관적인 방법을 제공한다.

 

먼저, json 파일이 준비되어 있다.(data.json)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[
    {
        "name":"홍길동",
        "age":24,
        "address":"서울시",
        "phone":"123"
    },
    {
        "name":"성춘향",
        "age":16,
        "address":"남원시",
        "phone":"234"
    },
    {
        "name":"홍두께",
        "age":22,
        "address":"강릉시",
        "phone":"345"
    }
]
cs

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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">button</button>
 
<script type="text/javascript">
 
    $("button").click(function(){
        
        $.ajax({
            // 요청
            url:"data.json",   // 클라이언트가 HTTP 요청을 보낼 URL 주소
            type:"get",        // HTTP 요청 방식(GET, POST)
            datatype:"json",   // 서버에서 보내줄 데이터의 타입
            
            // 데이터 
            success: function(data){
//                 alert("success");
//                 alert(data);
//                 alert(JSON.stringify(data));
                for(i = 0; i < data.length; i++){
                $("#demo").append((i + 1+ " ");
                $("#demo").append(data[i].name + " ");
                $("#demo").append(data[i].age + " ");
                $("#demo").append(data[i].address + " ");
                $("#demo").append(data[i].phone + "<br>");
                }
            },
            error: function(){
                alert("error");
            },
        });
        
    });
    
 
</script>
</body>
</html>
cs

 

그 결과 버튼을 누르면,

 

또 하나의 예제를 살펴보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
// JDBC -> 데이터를 산출
 
String name = "홍길동";
int age = 24;
String birth = "2001/06/17";
 
// json + 내장객체
 
String str = "{ \"name\":\"" + name + "\", \"age\":" + age + ", \"birth\":\"" + birth + "\" }";
 
out.println(str); // { "name":"홍길동", "age":24, "birth":"2001/06/17" }
%>
 
cs
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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="name"></p>
<p id="age"></p>
<p id="birth"></p>
<br>
<button type="button">button</button>
 
<script type="text/javascript">
$(function () {
    
    $("button").click(function(){
        
        $.ajax({
            url:"data.jsp"// 클라이언트가 HTTP 요청을 보낼 URL 주소
            type:"get"// HTTP 요청 방식(GET, POST)
            datatype:"json"// 서버에서 보내줄 데이터의 타입
            success:function(data){
//                  alert('success');
//                  alert(data.trim());
                let json = JSON.parse(data);
//                     alert(json);
                $("#name").text(json.name);
                $("#age").text(json.age);
                $("#birth").text(json.birth);
            
            },
            error:function(){
                alert('error');    
            }
        });
        
    });
});
</script>
 
 
</body>
</html>
 
 
 
 
 
cs

 

그 결과 버튼을 누르면,

 

 

 

 

 

 

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
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>
</head>
<body>
 
 
<p id="demo"></p>
 
<script type="text/javascript">
 
    let str = '{"name":"홍길동", "age":24, "address":"서울시"}' // string
//     alert(str)
     
     // string -> json 이를 parsing이라고 함
//      let json = JSON.parse(str); // json으로 만들어줌(parsing)
//     alert(json)
 
//     document.getElementById("demo").innerHTML = json.address; // json(객체).address(key값)
     
let json = [
    {
        "name":"홍길동",
        "age":24,
        "height":172.2
    },
    {
        "name":"성춘향",
        "age":16,
        "height":156.9
    },
    {
        "name":"일지매",
        "age":22,
        "height":181.3
    },
];
 
document.getElementById("demo").innerHTML = json[1].name + " " + json[1].height;
// 성춘향 156.9
    
</script>
 
</body>
</html>
cs

NBAjson.json이라는 파일을 가져와서 원하는 값들에 접근해보도록 하자.

NBAjson.json 파일은 아래와 같다.

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
{
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is correct team name in NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriors",
                    "Huston Rocket"
                ],
                "answer": "Huston Rocket"
            }
        },
        "maths": {
            "q1": {
                "question": "5 + 7 = ?",
                "options": [
                    "10",
                    "11",
                    "12",
                    "13"
                ],
                "answer": "12"
            },
            "q2": {
                "question": "12 - 8 = ?",
                "options": [
                    "1",
                    "2",
                    "3",
                    "4"
                ],
                "answer": "4"
            }
        }
    }
}
cs

위 파일을 활용하여,

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<span id="sport1"></span><br>
<span id="sport2"></span>
<br><br>
 
<span id="q1a"></span><br>
<span id="q1b"></span>
<br><br>
 
<span id="q2a"></span><br>
<span id="q2b"></span>
 
<script type="text/javascript">
 
let xhttp = new XMLHttpRequest();
 
xhttp.onreadystatechange = function() {
    
    if(xhttp.readyState == 4 && xhttp.status == 200){
        nbaFunc(this.responseText); // responseText는 문자열로 데이터를 받는다.
    }
}
xhttp.open("GET""NBAjson.json"true);
xhttp.send();
 
function nbaFunc(resp){
    // json으로 parsing
    let json = JSON.parse(resp); // string -> json
//     let str = JSON.stringify(json) // json -> string
 
    // sport의 question에 접근
    document.getElementById('sport1').innerHTML = "Question: " + json.quiz.sport.q1.question + " ";
    document.getElementById('sport2').innerHTML = "Answer: " + json.quiz.sport.q1.options[3];
    // 위 코드를 아래와 같이 사용할 수 있다. (quiz.sport 대신 quiz["sport"])
    // document.getElementById('sport2').innerHTML = "Answer: " + json.quiz["sport"].q1.options[3];
    
    // maths의 q1에 접근
    document.getElementById('q1a').innerHTML = "Question: " + json.quiz.maths.q1.question;
    document.getElementById('q1b').innerHTML = "Answer: " + json.quiz.maths.q1.options[2];
    
    // maths의 q2에 접근
    document.getElementById('q2a').innerHTML = "Question: " + json.quiz.maths.q2.question;
    document.getElementById('q2b').innerHTML = "Answer: " + json.quiz.maths.q2.options[3];
    
}
 
 
</script>
</body>
</html>
cs

결과는 다음과 같다.

 

<영화 5편에 대한 제목, 평점, 개봉일, 감독에 대한 정보를 나타낸 표 만들기>

먼저, json 파일을 살펴보면, 

movie.json

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
[
    {
        "title":"아바타",
        "score":8.83,
        "openday":"2022.12.14",
        "director": "제임스 카메론"
    },
    {
        "title":"범죄도시2",
        "score":9.00,
        "openday":"2022.05.18",
        "director": "이상용"
    },
    {
        "title":"극한직업",
        "score":9.20,
        "openday":"2019.01.23",
        "director": "이병헌"
    },
    {
        "title":"어벤져스",
        "score":9.50,
        "openday":"2019.04.24",
        "director": "안소니 루소"
    },
    {
        "title":"명량",
        "score":8.88,
        "openday":"2014.07.30",
        "director": "김한민"
    }
]
cs

 

테이블을 작성하는 코드는 아래와 같다.

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
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<div id="movies">
</div>
 
<script type="text/javascript">
 
let xhttp = new XMLHttpRequest();
 
xhttp.onreadystatechange = function () {
    if(this.readyState == 4 && this.status == 200){
        movieFunc( this );
    }    
}
xhttp.open("GET""movie.json"true);
xhttp.send();
 
function movieFunc( resp ) {    
    let jsonDoc = resp.responseText;
    // alert(jsonDoc);
    
    let json = JSON.parse(jsonDoc);    // parsing
    // alert(json);
    
    let table = "<table border='1'>";
    table += "<col width='50'><col width='100'><col width='80'><col width='100'><col width='140'>";
    
    table += "<tr>";
    table += "<th>번호</th>";
    
    for(key in json[0]){
        table += "<th>" + key + "</th>";    
    }
    
    table += "</tr>";
    
    // datas
    
    for(i = 0;i < json.length; i++){
    
        table += "<tr>";        
        table += "<th>" + (1 + i) + "</th>";
        
        // 아바타에 대한 정보만 나옴
        // table += "<td>" + json[0].title + "</td>";
        // table += "<td>" + json[0].score + "</td>";
        // table += "<td>" + json[0].openday + "</td>";
        // table += "<td>" + json[0].director + "</td>";
        
        for(key in json[i]){
            table += "<td>" + json[i][key] + "</td>";
        }
        
        table += "</tr>";
    }
    
    table += "</table>";    
    
    document.getElementById("movies").innerHTML = table;    
}
 
</script>
 
 
</body>
</html>
 
 
 
 
 
cs

 

그 결과는

도서 5권에 대해서 제목, 저자, 출판일, 가격에 대한 정보를 나타내는 표를 xml파일을 가져와 만들어보자.

 

첫번째로, xml파일을 만든다. (파일명: books.xml)

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
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <title>Java의 정석</title>
        <author>남궁성</author>
        <date>2016/06/17</date>
        <price>30000</price>
    </book>
  <book>
        <title>이것이 MySQL이다</title>
        <author>우재남</author>
        <date>2022/06/14</date>
        <price>32000</price>
    </book>
  <book>
        <title>미움 받을 용기</title>
        <author>기시미 이치로</author>
        <date>2022/12/28</date>
        <price>14310</price>
    </book>
  <book>
        <title>멈추면, 비로소 보이는 것들</title>
        <author>혜민</author>
        <date>2017/03/15</date>
        <price>12600</price>
    </book>
  <book>
        <title>완벽하지 않은 것들에 대한 사랑</title>
        <author>혜민</author>
        <date>2016/02/03</date>
        <price>13320</price>
    </book>
    
</books>
cs

위 코드에 간단한 설명을 덧붙이자면, 

<?xml version="1.0" encoding="UTF-8"?> 는 XML 프롤로그(prolog)

<books> 부터 </books>는 XML 요소

XML은 HTML과 같이 트리(tree) 형태의 계층 구조를 가진다. 따라서, <books>는 루트(root) 요소에 해당한다.

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
    <div id="demo"></div>
 
    <script type="text/javascript">
        let xhttp = new XMLHttpRequest();
 
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                xmlProc(xhttp);
            }
        }
        xhttp.open("GET""books.xml"true);
        xhttp.send();
 
        function xmlProc(xml) {
 
            let xmlDoc = xml.responseXML;
            let rootTagName = xmlDoc.documentElement.nodeName;
            let nodeArr = xmlDoc.documentElement.childNodes;
            let nodeName;
            for (i = 0; i < nodeArr.length; i++) {
                if (nodeArr[i].nodeType == 1) {
                    nodeName = nodeArr[i].nodeName;
                    console.log(nodeName);
                }
            }
            let table = "<table border='1'>";
            table += "<col width='50'><col width='100'><col width='140'><col width='100'><col width='140'>";
            table += "<tr>";
            table += "<th>번호</th>";
            columnName = xmlDoc.getElementsByTagName(nodeName)[0];
 
            let child = columnName.firstChild;
            console.log(columnName.childNodes.length);
 
            for (i = 0; i < columnName.childNodes.length; i++) {
                if (child.nodeType == 1) {
                    table += "<th>" + child.nodeName + "</th>";
                    console.log(child.nodeName);
                }
                child = child.nextSibling;
            }
            table += "</tr>";
            let len = xmlDoc.getElementsByTagName(nodeName).length;
 
            for (i = 0; i < len; i++) {
 
                table += "<tr>";
                table += "<th>" + (1 + i) + "</th>";
 
                let dataArr = xmlDoc.getElementsByTagName(nodeName)[i];
 
                child = dataArr.firstChild;
                for (j = 0; j < dataArr.childNodes.length; j++) {
                    if (child.nodeType == 1) {
                        table += "<td>" + child.childNodes[0].nodeValue
                                + "</td>";
                    }
                    child = child.nextSibling;
                }
 
                table += "</tr>";
            }
 
            table += "</table>"
 
            document.getElementById("demo").innerHTML = table;
        }
    </script>
 
 
</body>
</html>
cs
 

먼저, <div id="demo"></div>를 작성하여 완성된 table이 위치할 공간을 만든다.

 

<script>안의 코드들을 부분씩 떼어내서 살펴보면,

아래 코드는 자바스크립트를 사용해서 XMLHttpRequest 객체를 전송하는 것이다. 

1
2
3
4
5
6
7
8
9
let xhttp = new XMLHttpRequest();
 
xhttp.onreadystatechange = function () {
    if(this.readyState == 4 && this.status == 200){
        xmlProc( xhttp );
    }    
}
xhttp.open("GET""books.xml"true);
xhttp.send();
cs

1. XMLHttpRequest 객체의 생성

 XMLHttpRequest 객체는 서버로부터 XML 데이터를 전송받아 처리하는 데 사용된다.

 

2. xhttp.onreadystatechange = function() {

    }

onreadystatechange와 연결된 이벤트 핸들러 코드를 추가한다.

onreadystatechange 프로퍼티는 XMLHttpReuest 객체의  readyState 프로퍼티의 값이 변할 때마다 자동으로 호출되는 함수를 설정한다. 

이때, readyState 프로퍼티란 XMLHttpRequest 객체의 현재 상태를 나타낸다.

객체의 현재 상태에 따라서 다음과 같은 주기로 변화하는데,

 - UNSENT (숫자 0) : XMLHttpRequest 객체가 생성됨.

 - OPENED (숫자 1) : open() 메소드가 성공적으로 실행됨.

 - HEADERS_RECEIVED (숫자 2) : 모든 요청에 대한 응답이 도착함.

 - LOADING (숫자 3) : 요청한 데이터를 처리 중임.

 - DONE (숫자 4) : 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됨.

 

3. if(this.readyState == 4 && this.status == 200){
        xmlProc( xhttp );
    }

 2번에서 설명한 것과 같이 this.readyState == 4는 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됐음을 의미한다. 이는 this.readyState == this.DONE으로 대체할 수 있다.

 xmlProc( xhttp );는 이후 코드에서 xmlProc() 함수를 정의하여 사용한다.

 

4. open(), send()

open(method, url, async)을 이용했다.

이때, method는 요청방식으로 GET 또는 POST 방식이 있다.

GET 방식은 POST 방식보다 간단하고 빠르며, 대부분 경우에 사용이 가능하다.

url은 불러올 파일의 주소를 적는다.

async는 true(비동기) 또는 false(동기)를 적는데, 서버 요청은 true를 사용해야 하고, true(비동기)의 경우 JavaScript는 서버 응답을 기다릴 필요가 없으며 서버 응답을 기다리는 동안 다른 작업을 수행하다가 응답이 준비되면 처리가 가능하다.

open()에서 GET 방식을 사용했기 때문에 send()를 사용하여 서버에 요청을 보내도록 한다.

 

이후 코드들에 대해서는 주석을 통해 설명하도록 한다.

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Books</title>
</head>
<body>
 
<div id="demo">
</div>
 
<script type="text/javascript">
 
let xhttp = new XMLHttpRequest();
 
xhttp.onreadystatechange = function () {
    if(this.readyState == 4 && this.status == 200){
        xmlProc( xhttp );
    }    
}
xhttp.open("GET""books.xml"true);
xhttp.send();
 
function xmlProc( xml ) {
    // responseXML 프로퍼티: 서버에 요청하여 응답으로 받은 데이터를  XML DOM 객체로 저장한다.
    let xmlDoc = xml.responseXML; // 요청한 데이터를 XML DOM 객체로 반환함
    
    // root명 취득
    // xmlDoc.documentElement: xmlDoc의 루트 요소를 반환
    // xmlDoc.documentElement.nodeName: xmlDoc의 루트 요소의 노드 이름을 반환
    let rootTagName = xmlDoc.documentElement.nodeName;
    // alert(rootTagName); // books
    
    // node명 취득
    // xmlDoc.documentElement.childNodes: xmlDocdml 자식 노드 리스트를 반환
    let nodeArr = xmlDoc.documentElement.childNodes;
    console.log(nodeArr.length); // <book>과 텍스트 노드의 개수 등의 개수
    // node list 확인
    // nodeArr(자식 노드 리스트)에는 각 요소 다음에 별도의 텍스트 노드가 존재한다. 따라서, nodeType 프로퍼티를 통해 요소 노드만 선택하도록 한다.
    // 요소 노드의 경우 nodeType 프로퍼티 값이 1이다.
    let nodeName;
    for(i = 0;i < nodeArr.length; i++){
        if(nodeArr[i].nodeType == 1){
            nodeName = nodeArr[i].nodeName; // 요소 노드들의 이름을 반환
            console.log(i); // 요소 노도들의 인덱스
            console.log(nodeName); // <book>
        }
    } 
    
    // table을 준비
    let table = "<table border='1'>";
    table += "<col width='50'><col width='100'><col width='140'><col width='100'><col width='140'>";
    
    table += "<tr>"// 1번째 row 시작
    
    // column명(tag명)을 취득
    // getElementsByTagName("태그명"): 특정 태그 이름을 가지는 모든 요소를 노드 리스트의 형태로 반환합니다.
    columnName = xmlDoc.getElementsByTagName(nodeName)[0]; // <book> 5개중 첫번째 <book>
    console.log(columnName); 
    // 콘솔 결과
    // <book>
    //     <num>1</num>
    //     <title>Java의 정석</title>
    //     <author>남궁성</author>
    //     <date>2016/06/17</date>
    //     <price>30000</price>
    // </book>
    let child = columnName.firstChild;
    console.log(columnName.childNodes.length); // 11
    console.log(child); // #text
    
    for(i = 0;i < columnName.childNodes.length; i++){
        if(child.nodeType == 1){ // 요소 노드들만 선택되도록
            table += "<th>" + child.nodeName + "</th>";    
            console.log(child.nodeName);
        }        
        child = child.nextSibling; // nextSibling: 다음 요소를 반환(요소, 텍스트 등)
    }        
    table += "</tr>"// 1번째 row 끝
    
    // data 출력 // 2~6번째 row들
    let len = xmlDoc.getElementsByTagName(nodeName).length;
    console.log(len);
    console.log(xmlDoc.getElementsByTagName(nodeName)[1]);
    // 콘솔 결과
    // <book>
    //     <num>2</num>
    //     <title>이것이 MySQL이다</title>
    //     <author>우재남</author>
    //     <date>2022/06/14</date>
    //     <price>32000</price>
    // </book>
 
    for(i = 0;i < len; i++){
    
        table += "<tr>";
        
        let dataArr = xmlDoc.getElementsByTagName(nodeName)[i];
        
        child = dataArr.firstChild;
        for(j = 0;j < dataArr.childNodes.length; j++){
            if(child.nodeType == 1){
                table += "<td>" + child.childNodes[0].nodeValue + "</td>";
            }
            child = child.nextSibling;
        }
        
        table += "</tr>";
    }
    
    table += "</table>"
    
    
    document.getElementById("demo").innerHTML = table;    
}
 
 
    
</script>
 
 
</body>
</html>
 
 
 
 
 
 
 
 
 
 
 
cs

 

 

 

 

 

 

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<!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>
</head>
<body>
 
<h3>변수의 연산</h3>
a, b에 대해서 변수 a와 b의 계산 결과를 표시합니다.
<br><br>
 
<button type="button" onclick="proc(1)">덧셈</button>
<button type="button" onclick="proc(2)">뺄셈</button>
<button type="button" onclick="proc(3)">곱셈</button>
<button type="button" onclick="proc(4)">나눗셈</button>
<button type="button" onclick="proc(5)">나머지</button>
<br><br>
 
<input type="text" id="a" size="10">
<input type="text" id="oper" size="5" readonly="readonly">
<input type="text" id="b" size="10">
=
<input type="text" id="result" size="20" readonly="readonly">
 
<script>
function proc(oper){
  // 빈칸 조사
  let a_val = document.getElementById('a').value;
    let b_val = document.getElementById('b').value;
  
  if(a_val.trim() == "" || b_val.trim() == ""){
        alert('숫자를 입력해 주십시오');
        return;
    }
 
  let a =  parseInt(document.getElementById('a').value);
  let b =  parseInt(document.getElementById('b').value);
  let result = 0;
  let op = "+";
 
  if(oper == 1) {
    result = a + b;
    op = "+";
  }
  else if(oper == 2) {
    result = a - b;
    op = "-";
  }
  else if(oper == 3) {
    result = a * b;
    op = "*";
  }
  else if(oper == 4) {
    if( b == 0) {
      alert("계산할 수 없습니다. 다시 입력해주세요");
      document.getElementById('b').value = "";
      return;
    }
    result = a / b;
    op = "/";
  }
  else {
    if( b == 0) {
      alert("계산할 수 없습니다. 다시 입력해주세요");
      document.getElementById('b').value = "";
      return;
    }
    result = a % b;
    op = "%";
  }
 
  document.getElementById("oper").value = op;
    document.getElementById("result").value = result;    
 
}
 
</script>
 
</body>
</html>
cs

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<!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>
</head>
<body>
<h1>체육관 이용요금</h1>
기본사용료(4시간)40,800원
<br><br> 
<!-- <div>
<input type="checkbox" onclick="sum(0)" id="chk1" value="20000">
<label for="chk1">야간조명(20,000원)</label>
</div>
<div>
<input type="checkbox" onclick="sum(1)" id="chk2" value="4000">
<label for="chk1">배구네트 x 2장(4,000원)</label>
</div>
<div>
<input type="checkbox" onclick="sum(2)" id="chk3" value="5000">
<label for="chk1">배구공 x 10(5,000원)</label>
</div>
<br><br>
<label for="total">합계금액:</label>
<input type="text" id="total" value="40800">
<label for="total">원정</label>
 
<script>
  let total = parseInt(document.getElementById("total").value);
 
  function sum(num){
    if(num == 0){
      // 체크박스 체크되어 있으면 true, 체크 해제되면 false 반환(checked 이용)
      let chk1 = document.getElementById("chk1").checked; 
      let value = parseInt(document.getElementById("chk1").value);
 
      if(chk1 == true){
        total += value;
      }
      else {
        total -= value;
      }
      document.getElementById("total").value = total;
    }
    else if(num == 1){
      let chk2 = document.getElementById("chk2").checked;    
      let value = parseInt( document.getElementById("chk2").value );        
      
      if(chk2 == true){
        total = total + value;
      }else{
        total = total - value;
      }
      document.getElementById("total").value = total;
      }
    else if(num == 2){
      let chk3 = document.getElementById("chk3").checked;            let value = parseInt( document.getElementById("chk3").value );        
 
      if(chk3 == true){
        total = total + value;
      }else{
        total = total - value;
      }
      document.getElementById("total").value = total;
      }
  }
</script> -->
<form name="frm">
  <input type="checkbox" onclick="sum(0)" id="chk1" value="20000">야간조명(20,000원)
    <br>
    <input type="checkbox" onclick="sum(1)" id="chk2" value="4000">배구네트 x 2장(4,000원)
    <br>
    <input type="checkbox" onclick="sum(2)" id="chk3" value="5000">배구공 x 10(5,000원)
    <br><br>
    합계금액:<input type="text" id="total" value="40800">원정
</form>
 
<script>
  let array = new Array(3);
  array[0= parseInt(document.getElementById("chk1").value);
  array[1= parseInt(document.getElementById("chk2").value);
  array[2= parseInt(document.getElementById("chk3").value);
 
  let total = parseIntdocument.getElementById("total").value );
 
  function sum( num ) {
  if(document.frm.elements[num].checked == true){
        total += array[num];
    }
  else{
        total -= array[num];
    }
    document.frm.elements[3].value = total;
}
</script>
 
 
</body>
</html>
cs

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
<!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>
</head>
<body>
 
<h1>2개의 주사위</h1>
버튼을 클릭하면 2개의 주사위가 랜덤됩니다
<br><br>
 
<img alt="" src="./images/sai_1.gif" id="d1">
<img alt="" src="./images/sai_6.gif" id="d2">
 
<br><br>
<button type="button" onclick="dice()">주사위를 던졌다</button>
 
<script>
function dice(){
  let r1 = Math.floor(Math.random() * 6+ 1;
  let r2 = Math.floor(Math.random() * 6+ 1;
 
  document.getElementById("d1").src = "./images/sai_" + r1 + ".gif";
  document.getElementById("d2").src = "./images/sai_" + r2 + ".gif";
}
 
</script>
 
</body>
</html>
cs

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
<!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>
  <style>
    body{
      background-color: black;
      margin: 20px;
    }
    h1,span{
      color: white;
    }
    td{
      vertical-align: top;
    }
    img{
      border: solid white;
    }
  </style>
 
</head>
<body>
  <h1>사진들</h1>
 
  <table>
    <tr>
      <td>
        <img alt="" width="320" height="480" id="photo" src="./images/image01.jpg">
      </td>
      <td>
        <span>사진의 선택</span><br>
        <select id="picture" onchange="photoChange()">
          <option selected>사진선택</option>
          <option value="image01.jpg">일반건물밖</option>
          <option value="image02.jpg">일반건물안</option>
          <option value="image03.jpg">성당밖</option>    
          <option value="image04.jpg">성당안</option>    
        </select>
      </td>
    </tr>
  </table>
 
<script>
function photoChange(){
  let picture = document.getElementById("picture").value;
 
    let selectIndex = document.getElementById("picture").selectedIndex;
  if(selectIndex != 0){        
        document.getElementById("photo").src = "./images/" + picture;
    }
}
 
 
</script>
</body>
</html>
cs

 

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
<!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>
</head>
<body>
 
<h1>미술관 및 박물관 링크</h1>
 
<select id="links" onchange="golink()">
  <option>대상을 선택</option>
  <optgroup label="미술관------------">
    <option value="http://sema.seoul.go.kr/">서울 시립 미술관</option>
    <option value="http://www.mmca.go.kr/ ">국립 현대 미술관</option>
    <option value="http://www.sac.or.kr/">예술의 전당</option>
  </optgroup>
  <optgroup label="박물관------------">
    <option value="http://www.museum.go.kr/">국립 중앙 박물관</option>
    <option value="http://www.museum.seoul.kr/">서울 역사 박물관</option>
    <option value="http://www.nfm.go.kr/">국립 민속 박물관</option>
  </optgroup>
</select>
 
<script>
function golink(){
  let url = document.getElementById("links").value;
  location.href = url;
}
 
</script>
 
</body>
</html>
cs

 

 

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
<!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>
</head>
<body>
 
<h3>단가 X 수량 일람표</h3>
 
<table border="1" id="mytable">
  <tr>
    <th>번호</th>
    <th>제품 A</th>
    <th>제품 B</th>
    <th>제품 C</th>
  </tr> 
 
</table>
 
<script>
 
let arrA = [ 2345113627 ];
let arrB = [ 3129731278 ];
let arrC = [ 3628331285 ];
 
let table = document.getElementById("mytable");
 
for(i = 0; i < arrA.length; i++){
let tr = document.createElement("tr");
let th = document.createElement("th");
th.appendChild(document.createTextNode(1 + i + ""));
 
let td1 = document.createElement("td");
td1.appendChild(document.createTextNode(arrA[i] + ""));
let td2 = document.createElement("td");
td2.appendChild(document.createTextNode(arrB[i] + ""));
let td3 = document.createElement("td");
td3.appendChild(document.createTextNode(arrC[i] + ""));
 
tr.appendChild(th);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
 
table.appendChild(tr);
}
 
 
</script>
 
</body>
</html>
cs

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<!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>
<style>
  td{
    text-align: center;
  }
</style>
 
</head>
<body>
 
<h3>배열의 연산</h3>
 
<table border="1">
<col width="50"><col width="80"><col width="80"><col width="100">
 
<thead>
  <tr>
      <th>번호</th>
      <th>a</th>
      <th>b</th>
      <th>a x b</th>
  </tr>
</thead>
 
<tbody>
  <tr>
    <th>0</th>
    <td>5</td>
    <td>33</td>
    <td>
      <button type="button" onclick="multi(0)">계산결과</button>
    </td>
  </tr>
  <tr>
    <th>1</th>
    <td>12</td>
    <td>14</td>
    <td>
      <button type="button" onclick="multi(1)">계산결과</button>
    </td>
  </tr>
  <tr>
    <th>2</th>
    <td>18</td>
    <td>32</td>
    <td>
      <button type="button" onclick="multi(2)">계산결과</button>
    </td>
  </tr>
 
</tbody>
</table>
 
<script>
 
let nodeNumbers = document.getElementsByTagName("td");
// alert(nodeNumbers[0].innerHTML);
// (0 1) (3 4) (6 7)번지 값들만 필요
 
let a = new Array(3);
let b = new Array(3);
 
for(i=0; i < a.length; i++){
  a[i] = nodeNumbers[3*i].innerHTML;
  b[i] = nodeNumbers[1+3*i].innerHTML;
}
 
function multi(index){
  let result = parseInt(a[index]) * parseInt(b[index]);
  alert('결과는 ' + result + '입니다.');
}
 
 
</script>
 
 
</body>
</html>
cs

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
<!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>
</head>
<body>
 
<h3>10진수를 2진수, 8진수, 16진수로 변환</h3>
 
<table>
<tr>
  <th>10진수:</th>
  <td>
    <input type="text" size="30" id="num10">
  </td>
</tr>
<tr>
  <th>2진수:</th>
  <td>
    <input type="text" size="30" id="num2">
  </td>
</tr>
<tr>
  <th>8진수:</th>
  <td>
    <input type="text" size="30" id="num8">
  </td>
</tr>
<tr>
  <th>16진수:</th>
  <td>
    <input type="text" size="30" id="num16">
  </td>
</tr>
</table>
<br>
<button type="button" onclick="proc()">결과</button>
 
<script>
function proc(){
  let num10 = parseInt(document.getElementById("num10").value);
 
  document.getElementById("num2").value = num10.toString(2);
 
  document.getElementById("num8").value = "0" + num10.toString(8);
 
  document.getElementById("num16").value = "0x" + num10.toString(16).toUpperCase();
 
}
 
 
</script>
 
 
 
 
</body>
</html>
cs

 

+ Recent posts