Scenario: 로그인을 원래 쌩 jsp로 구성을 해보았엇는데 생각보다 많은게 필요하다.

만약 Jsp로 구성한다면

로그인 -> 로그인ok(로그인이 성공했는지 확인 page) -> 성공시 main

(중간에 jsp 페이지를 안두고 구현 해볼려고했는데, 로그인 실패시 alert 창을 띄울수가 없었다.(엄청 고민해봤는데 결국 포기))

이런식으로 중간에 jsp 페이지를 하나 더 거처야한다. 그러나 Ajax로 구현하면 동적으로 할 수있다.

그리고 페이지또한

로그인->성공시 main 실패시 그냥 alert 창 하나만 띄워주면 됐다. 아주 간편하다.


Solutions:

Ajax 구문

jQuery 0.61 KB
  1. $('#btn_login').click(function() {
  2.  
  3.           var mid = $('#txt_mid').val();
  4.  
  5.           var psw = $('#txt_psw').val();
  6.  
  7.           $.ajax({
  8.  
  9.               type : "POST",
  10.  
  11.               url : "/BoardProject/login.ref",
  12.  
  13.               data : "mid=" + mid + "&psw=" + psw,
  14.  
  15.               dataType : "text",
  16.  
  17.               success : function(data, textStatus, xhr) {
  18.  
  19.                  if (data == 'loginFail') {
  20.  
  21.                       alert('로그인에 실패하였습니다.')
  22.  
  23.                   } else {
  24.  
  25.                       window.location.href = 'main.jsp';
  26.  
  27.                   }
  28.  
  29.               },
  30.  
  31.               error : function(request, status, error) {
  32.  
  33.                   alert("code:" + request.status + "\n" + "error:" + error);
  34.  
  35.               }
  36.  
  37.           })
  38.  
  39. });



controller 단 (servlet으로 프로젝트를 하던 소스코드이므로 스프링에는 다르게 적용할것)

Java 0.72 KB
  1. public class BoardLoginCommand implements BoardCommand{
  2.  
  3.     @Override
  4.     public void execute(HttpServletRequest request, HttpServletResponse response) {
  5.         String mid = request.getParameter("mid");
  6.         String password = request.getParameter("psw");
  7.         System.out.println("id"+mid+",pw"+password);
  8.         HttpSession session = request.getSession();
  9.        
  10.         DAO dao = new DAO();
  11.         ArrayList<DTO> list = dao.loginMember(mid, password);
  12.         System.out.println(list);
  13.         if(list.isEmpty()){
  14.             System.out.println("로그인안됨");
  15.             try {
  16.                 response.getWriter().write("loginFail");
  17.             } catch (IOException e) {
  18.                 e.printStackTrace();
  19.             }
  20.         }else{
  21.         request.setAttribute("list", list);
  22.         session.setAttribute("mid", mid);
  23.         }
  24.     }
  25.  
  26. }


Scenario: 사정상 Spring이 아닌 '무려' 서블릿으로 프로젝트를 진행하게 되었다. 너무 비효율적이고 힘들었지만 그래도 해내야만 했다.

그러다가 리플을 블러오는 기능을 동적으로 구현 하려고 ajax를 쓰려고 했는데, 스프링에서는 그냥 return값을 map으로 해주면 됬는데, 

이거 servlet은 return 값을 따로 넣어줄수가 없었다. (ViewPage를 넣어주면 무조건 redirect가 되버리므로 아주 복잡해졌다.)

그래서 command단에서 return으로 끝내버리고 끝내기전에 list<dto> 객체를 보내주어야 했다 (리플이 들어있는) 



Solution: 일단 list<dto>를 jason형태로 바꾸면 됐다. 이 부분은 구글의 Gson 라이브러리를 받아 해결 할 수 있었다.


view단 (ajax부분)

jQuery 0.59 KB
  1.   $.ajax({
  2.      type : "POST",
  3.      url : "/BoardProject/listreply.ref",
  4.      data : "BID="+selBid,
  5.      dataType: "json", !-- 꼭 jason으로 할 것 찍어주는 부분 -->
  6.      success : function(data, textStatus, xhr) {
  7.          $('#reply').empty();
  8.          $.each(data, function(key, val){
  9.              <!-- 로그 찍어주는 부분 -->
  10.              console.log('key:' + key + ' / ' + 'value:' + val['reply']);
  11.              $('#reply').append(val['reply']+'<br>');
  12.          });
  13.      },
  14.      error : function(request,status,error) {  
  15.         alert("code:"+request.status+"\n"+"error:"+error);
  16.      }
  17.   });



Contorller단 (command 오랜만에쓰는 부분)

Java 0.91 KB
  1. public class BoardReplyListCommand implements BoardCommand {
  2.     @Override
  3.     public void execute(HttpServletRequest request, HttpServletResponse response) {
  4.            
  5.             DAO dao = new DAO();
  6.             String bid = request.getParameter("BID");
  7.             System.out.println(bid);
  8.             ArrayList<DTO> list = dao.listreply(bid);
  9.             request.setAttribute("rlist", list);
  10.            
  11.             //타입을 json으로 바꿔줘야됨
  12.             response.setContentType("application/json");
  13.             response.setCharacterEncoding("UTF-8");
  14.            
  15.             //DTO 타입의 어레이리스트를 json 형태로 바꿔주는 구문(라이브러리 필수, zip->jar 확장자명 꼭 확인)
  16.             String gson = new Gson().toJson(list);
  17.            
  18.             try {
  19.                 //ajax로 리턴해주는 부분
  20.                 response.getWriter().write(gson);
  21.             } catch (JsonIOException e) {
  22.                 e.printStackTrace();
  23.             } catch (IOException e) {
  24.                 e.printStackTrace();
  25.             }
  26.            
  27.     }
  28. }


Scenario: 메인에 Index.jsp 에서 2개의 프레임이 있다. 왼쪽은 로그인을 할 수 있는 iframe 이고 오른쪽은 로그인 결과를 나타내주는 iframe이다.

왼쪽창에서 로그인 검증값으로 넘어간뒤 로그인이 완료되면 right의 iframe 을 동적으로  반응 시켜주어야 했다. 

즉 왼쪽 iframe 스크립트 코드에서 오른쪽으로 접근하는 부분에서 애를 많이 먹었는데 성공 할 수있었다.


Solutions:

(구문해석)

$('#right', window.parent.document).contents().find('.login').show();    //가장 애먹은 부분이었다.

위와 왼쪽 프레임에서 오른쪽 프레임으로 접근하였다.

 $('#right', window.parent.document) 이것은 부모프레임에서 #right라는 id를 가진 프레임에 접근하는 것이다.

contents().find('.login').show(); 그뒤에 그 프레임내 컨텐츠에서 login class를 가진 요소에 접근해 show() 시켜준다.


<index.jsp>

HTML 5 0.54 KB
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.    pageEncoding="UTF-8"%>
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <title>Insert title here</title>
  7.  
  8. </head>
  9. <body>
  10. <h1 id=hi>여기표시 접근가능?</h1>
  11. <table width="100%" border="1">
  12. <tr><td id='frame'>
  13. <iframe src="left.jsp" width="450" height="560"></iframe>
  14. <iframe id="right" src="right.jsp" width="450" height="560"></iframe>
  15. </td>
  16. </tr>
  17. </table>
  18.  
  19. <script type="text/javascript">
  20.    
  21. </script>
  22. </body>
  23. </html>



<left.jsp>

HTML 5 1.65 KB
  1. <%@page import="java.util.Date"%>
  2. <%@page import="java.text.SimpleDateFormat"%>
  3. <%@ page language="java" contentType="text/html; charset=UTF-8"
  4.    pageEncoding="UTF-8"%>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <%
  9.     Date time = new Date();
  10.     SimpleDateFormat formatter = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
  11.  
  12. %>
  13. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  14. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  15.  
  16.  
  17. </head>
  18. <body>
  19.     <h1>left.jsp</h1><br>
  20.     <form action="LoginResult.jsp">
  21.         <% if(session.getAttribute("id") == null){%>
  22.        
  23.             아이디:  <input type="text" name="id"><br>
  24.             비밀번호: <input type="text" name="pw"><br>
  25.             <input type="submit" value="로그인">
  26.        
  27.         <script type="text/javascript">
  28.             $(function(){
  29.                 $('#right', window.parent.document).contents().find('.login').hide();
  30.                 $('#right', window.parent.document).contents().find('.logout').show();
  31.             })
  32.         </script>
  33.        
  34.        
  35.         <%} else { %>
  36.         <h3>jsp 님 로그인중</h3><br>
  37.         <input type="submit" value="LogOut">
  38.             <hr style="border:solid 2px red;">
  39.             접속시간:<% time.setTime(session.getCreationTime()); %><%=formatter.format(time) %><br>
  40.             최근 접근 시간시간:<% time.setTime(session.getLastAccessedTime()); %>
  41.             <%=formatter.format(time) %>
  42.                 <script type="text/javascript">
  43.             $(function(){
  44.                 $('#right', window.parent.document).contents().find('.login').show(); //제일 애먹었던부분
  45.                 $('#right', window.parent.document).contents().find('.logout').hide();
  46.             })
  47.         </script>  
  48.         <%}%>
  49.     </form>
  50. </body>
  51. </html>


<right.jsp>

HTML 5 0.59 KB
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.    pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10.     <h1>RIGHT.jsp</h1><br>
  11.     <h2 class='logout'>로그인되어 있지 않은 상태입니다.</h2>
  12.     <img class='login' alt="main" src="main.jpg" width="70%" height="70%" style="display:none">
  13.     <h2 class='login' style="display:none">접속중입니다.</h2>
  14. </body>
  15. </html>


<LoginResult.jsp> ->로그인 검증

HTML 5 1.02 KB
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.    pageEncoding="UTF-8"%>  
  3.  
  4.  
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>Insert title here</title>
  10. </head>
  11. <body>
  12.  
  13. <%
  14.     if("jsp".equals(request.getParameter("id")) && "1234".equals(request.getParameter("pw")))
  15.     {
  16.         session.getId();
  17.         session.setAttribute("id""jsp");
  18.         session.setAttribute("pw""1234");
  19. %>
  20.     <script type="text/javascript">
  21.         alert("로그인에 성공하였습니다.")
  22.         location.href="left.jsp";
  23.     </script>
  24. <%  } else {
  25.         if(session.getAttribute("id") != null)
  26.         {
  27.             session.invalidate();
  28. %>
  29.         <script type="text/javascript">
  30.             alert("로그아웃 되었습니다.");
  31.             location.href="left.jsp";
  32.         </script>
  33. <%      } %>
  34.         <script type="text/javascript">
  35.             alert("비밀번호가 틀렸습니다.");
  36.             location.href="left.jsp";
  37.         </script>
  38. <%} %>
  39.  
  40. </body>
  41. </html>






<접속 안되있을시>

<로그인 성공시>

알아야할 사전 지식.

1.Json 이란 무엇인가?

 JavaScript Object Notation의 약자로써, 자바스크립트를 위한 것이며, 객체 형식으로 자료를 표현하는 것이다. 그냥 [제이:슨] 이라고 읽으면 된다.

2.이것은 새로운 언어인가?

 아니다 단순히 데이터 포맷일 뿐이다. XML,INI 파일 등과 같은 비슷한 것이라고 생각하면 된다.




Scenario: Ajax를 이용해서 여러 데이터 파일을 파싱하고자함. 그중 첫번째는 json 파일


Solutions : (아래)


<Ajax_getjSON.html>

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>JSON 이용하기</title>
  6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  7. <script type="text/javascript">
  8.     $(function() {
  9. //      $.ajax({
  10. //          url: "items.json",
  11. //          contentType: "application/x-www-form-urlencoded; charset=UTF-8",
  12. //              dataType: "json",    
  13. //          success: function(result) {
  14. //              $.each(result, function(i, val) {
  15. //                  console.log(val['id']+':'+val['name']);
  16. //              })
  17. //          },
  18. //          error: function(jqXHR, textStatus, errorThrown) {
  19. //              alert("Error: " + textStatus + " errorThrown: " + errorThrown);
  20. //          }
  21. //      });
  22. //ajax 이용
  23.  
  24.         $.getJSON("items.json", function(result) {
  25.             $('#treeData').append("<tr><td>price</td>"+"<td>name</td>"+"<td>price</td>"+"<td>description</td></tr>");
  26.             $.each(result, function(i, val) { //result는 each 문에 val과 매칭시켜주기위함이고 , 인자 i와 val은 each함수의 시그니쳐다.
  27.                 console.log(typeof(i));
  28.                 console.log(val['id']+val['name']+val['price']+val['description']);
  29.                 $('#treeData').append("<tr><td>"+val['id']+"</td>"+"<td>"+val['name']+"</td>"+"<td>"+val['price']+"</td>"+"<td>"+val['description']+"</td></tr>");
  30.             });
  31.         });
  32. });  
  33. </script>
  34. <style>
  35. td, th {
  36.     border: 1px solid gray;
  37. }
  38. </style>
  39.  
  40. </head>
  41. <body>
  42.     <table id="treeData">
  43.     </table>
  44. </body>
  45. </html>


<items.json>

  1. [
  2.   {
  3.     "id": "1",
  4.     "name": "레몬",
  5.     "price": " 3000",
  6.     "description": "레몬에 포함되어 있는 쿠엔산은 피로회복에 좋다. 비타민C도 풍부하다."
  7.   },
  8.   {
  9.     "id": "2",
  10.     "name": "키위",
  11.     "price": " 2000",
  12.     "description": "비타민C가 매우 풍부하다. 다이에트와 미용에도 매우 좋다."
  13.   },
  14.   {
  15.     "id": "3",
  16.     "name": "블루베리",
  17.     "price": " 5000",
  18.     "description": "블루베리에 포함된 anthocyanin(안토시아닌)은 눈피로에 효과가 있다."
  19.   },
  20.   {
  21.     "id": "4",
  22.     "name": "체리",
  23.     "price": " 5000",
  24.     "description": "체리는 맛이 단 성분이 많고 피로회복에 잘 듣는다."
  25.   },
  26.   {
  27.     "id": "5",
  28.     "name": "메론",
  29.     "price": " 5000",
  30.     "description": "메론에는 비타민A와 칼륨이 많이 포함되어 있다."
  31.   },
  32.   {
  33.     "id": "6",
  34.     "name": "수박",
  35.     "price": "15000",
  36.     "description": "수분이 풍부한 과일이다."
  37.   }
  38. ]


어려웠던점 

1. 일단 Json 데이터의 {}가 한개일때는 파싱하기가 쉬운데, 중괄호가 여러개가 되니 하나의 오브젝트가 되어 파싱하기가 힘들어졌다. 

찾아보니  {}가 여러개인 형태를 json array라고 부른다고 하더라 (Json 데이터가 배열형태를 이룸), json array라는 키워드를 알고 구글링하니 찾기 쉬워짐

2.json 파일을 불러오다보니 한글파일이 자꾸 깨짐, 일단 결론부터 말하자면 .getJSON 으로는 utf-8 을 지정할 수 없음. .aJax를 쓰면 contentType key로 

utf-8 지정가능




+Tip 시그니쳐란 무엇인가?

나는 원래 C,C++ 부터 프로그래밍을 시작해서, 델리게이터를 만들때 시그너쳐(signature) 라는 용어를 많이썻었는데,

시그너쳐란 말그대로 어떤 함수의 선언문에  명시된 매개변수 리스트와 반환타입이다.

쉽게말해 시그니처는 함수의 형태이다.


[Signature Ex]

int getMoney(Person kim); 

다음 함수 에서 시그니쳐는 int(Person) 인것이다.


Scenario: Ajax를 이용하여, 특정 Html 요소 불러오기 그 Html 파일내에 특정 태그 요소만 불러오고자 함


Solutions: 제일 고민됬던 부분.1. $.ajax를 써서 어떻게 <li> 태그요소만 불러올것인가?? 나는 ajax name:value를 뒤져봤는데 아무리봐도 나오지 않았다.

결국 jquery 메소드를 통해 해결 할 수 있엇다.

총 소스는 (아래)

<Main.html>

  1. <head>
  2. <meta charset="UTF-8">
  3. <title>서버의 데이터를 대상 엘리먼트에 삽입하기</title>
  4. <style>
  5. div {
  6.     width: 200px;
  7.     height: 80px;
  8.     margin: 3px;
  9.     float: left;
  10. }
  11. </style>
  12. <script
  13.     src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  14. <script>
  15.     $(document).ready(function() {
  16.         $("#menu1").click(function() {
  17.             $.ajax({
  18.                 url : "menu.html",
  19.                 success : function(result) {
  20.                     $("#message1").html(result);
  21.                 }
  22.             });
  23.         });
  24.     });
  25.     $(document).ready(function() {
  26.         $("#menu2").click(function() {
  27.             $.ajax({
  28.                 url : "menu.html",
  29.                 success : function(result) {
  30.                     var refine = $("#message2").html(result).find('li');
  31.                     console.log(result);
  32.                     console.log(refine);
  33.                     console.log(typeof(refine));
  34.                     $('#message2').html(refine);
  35.                 }
  36.             });
  37.         });
  38.     });
  39. </script>
  40. </head>
  41. <body>
  42.     <div>
  43.         <a href="#" id="menu1">메뉴 보기 1</a>
  44.         <p>
  45.             <span id="message1"></span>
  46.     </div>
  47.     <div>
  48.         <a href="#" id="menu2">메뉴 보기 2</a>
  49.         <p>
  50.             <span id="message2"></span>
  51.     </div>
  52. </body>
  53. </html>

 

<menu.html> : main 에서 불러올 html 파일

  1. <meta charset="UTF-8">
  2.  
  3. <p> 중 식 메 뉴 </p>
  4. <ul>
  5. <li> 짜장면 </li>
  6. <li> 짬뽕 </li>
  7. <li> 기스면 </li>
  8. <li> 탕수육 </li>
  9. </ul>
  10. <p> 메뉴를 골라주세요.</p>


Scenario: 체크박스를 만들어 jQuery로  선택된 체크박스 value 들을 가져오고, 결과에 밑에 띄워준다. 두번째 부터는 결과에 있는 요소들을 지워준디 다시 그려준다.



Solutions: 아래


Ps. 어려웠던점

1. jQuery 선택자와 결과밑에 check value를 띄워줄때, 맨처음엔 after로 했엇는데 아무리해도 안지워 지는것이다. 여기서 많은 고민을함.

  차라리 Text 삽입시에 append를 사용하면 그 객체들이 전부 child 가 되기때문에 지워주기가 쉬움.


  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>여러 개의 취미를 체크박스에서 선택하고 결과보기-:checkbox</title>
  6. <style>
  7. div {padding: 5px 5px 5px 5px}
  8. .item { float: left;    width: 100px;}
  9. </style>
  10. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
  11.     <script type="text/javascript">
  12.     $(function(){
  13.         $('#selectBtn').click(function(){
  14. //          console.log(('#contents'));
  15.             $('#contents').children().text(""); //모든자식 지우기(새로 선택된결과를 띄우기위해서)
  16. //          $('#contents').children('p').text(""); P인자식만 해당
  17.              $('input:checkbox').each(function() { //[name=??] 로특정 체크박스만 불러오기가능
  18.                  if(this.checked)
  19.                     $('#contents').append('<p>'+this.value);
  20.              });
  21.         });
  22.     });
  23.    
  24.     </script>
  25.    
  26.  
  27. </head>
  28. <body>
  29.     <div>
  30.     <span class="item"> 음악감상 </span> <input type="checkbox" name="hobby" value="music">
  31.     </div>
  32.     <div>
  33.         <span class="item"> 요가 </span> <input type="checkbox" name="hobby"  value="yoga">
  34.     </div>
  35.     <div>
  36.         <span class="item"> 독서 </span> <input type="checkbox" name="hobby"  value="reading">
  37.     </div>
  38.     <div>
  39.         <input type="button" id="selectBtn" value="취미 선택">
  40.     </div>
  41.     <div id="contents">결과</div>
  42. </body>
  43. </html>


Scenario: 학원에서 공부한 jQuery 기본 셀렉터 예제 정리


Solutions: 아래


  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title> 객체 조작 및 생성 </title>
  6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> //CDN을 쓰면 궂이 JS파일 없이사용가능
  7. <style type="text/css">
  8. <script>
  9. //************* 기본 예제문제 시작
  10. $(function(){
  11. //(1) h1 태그의 align 속성값을 left적용하기
  12. $('h1').css("text-align","left");
  13. //(2): li태그중 첫번째 요소에 텍스트를 새 텍스틀 바꾸기
  14. $('li:eq(0)').text("첫번째리스트");
  15. //(3)h2태그에 자식 요소인 strong태그의 글자를 빨간색으로 적용
  16. $("h2:nth-child(2)").css("color","red");
  17. //(4)id=two인 요소의 이전 요소에 글자를 파란색으로 적용
  18. $("#two").css("color","blue");
  19. //(5)id=two인 요소의 다음에요소에 글자를 보라색으로 적용
  20. $("#two").next().css("color","purple");
  21. //(6)id=two인 요소의 부모 요소에 파선을 생성
  22. $("#two").parent().css("border","dashed");
  23. //(7)class=myList인 요소내의 가장 앞의 위치에 새요소를 추가
  24. $(".myList").prepend("<li>Front</li>");
  25. //(8)class=myList인 요소내의 마지막 위치에 새요소를 추가
  26. $(".myList").append("<li>back</li>");
  27. //(9)class=three인 요소의 이전 위치에 새요소를 생성
  28. $(".three").before("<li>앞에삽입</li>");
  29. //(10)class=three인 요소의 다음 위치에 새 요소를 생성
  30. $(".three").after("<li>뒤에삽입</li>");
  31. //(11)h2태그중에 2번째 요소를 <div>태그로 감싸기
  32. $("h2:nth-of-type(2)").wrap('<div/>');
  33. //(12)h2태그중에 하위 요소를 strong태그를 포함하는 <h2>에 class="tit"속성 추가
  34. $("h2").children("strong").parent().addClass('tit'); //** 가장애먹은부분("h2").children("strong") 에 tit를 추가하면 스트롱태그에만 tit추가하는거임.
  35. //(13)h2태그중에 마지막 요소에 class="tit"속성을 제거
  36. $("h2:last").removeClass('tit');
  37. });
  38.  
  39. //**************특정 배수 객체에 css적용시 셀렉터 사용법
  40.     $(function() {
  41.         $('h3:nth-child(3n+1)').css({'background-color':"black",'color':"white"}); //이렇게 +1을 해줘야지 0번째부터 시작됨
  42.         $('h3:nth-child(3n+1)').css({'background-color':"black",'color':"white"}); //중괄호 사용시 따옴표를 쓰지 않고
  43.                                                                       //backgroundColor:'balck' 이렇게 카멜표기법으로 표현가능
  44.     })
  45.  
  46.  
  47. //**********마이너스 선택자를 쓸경우 ; -1은 집합내 맨끝요소를 가르킴
  48. $(function() {
  49.         $('h1').css({'background-color':'orange','color':'white'}); //한줄에 이런식으로 css 여러속성 주기가능
  50.         $('h1').eq(-2).css('color',"red");  //'h1:eq(0)'처럼 쓰면 li태그 내에서만 셀렉 가능, 그러나 이런식으로하면 다 쓸수 있고
  51.                                             //인덱스가 0부터 시작.(n일경우)
  52. });
  53.  
  54.  
  55. //**********게시판 만들때 글 순서에따라 명암도 규칙있게 주기
  56. $(function() {
  57.     $('tr:nth-child(3n)').css({'background-color':"gray"}).prev().css({'background-color':"lightgray"});   
  58. })
  59.  
  60. </script>
  61. <style>
  62.    div{background-color:yellow;}
  63.    .tit{background-color:orange;}
  64. </style>
  65. </head>
  66. <body>
  67. // 생략된 객체들이 있음
  68.   <h1 align="center"><strong>내용1</strong></h1>
  69.   <h2><strong>내용2</strong></h2>
  70.   <h2>내용3</h2>
  71.   <h2 class="tit">내용4</h2>
  72.   <ul class="myList">
  73.     <li>리스트1</li>
  74.     <li id="two">리스트2</li>
  75.     <li class="three">리스트3</li>
  76.     <li>리스트4</li>
  77.   </ul>
  78.  
  79.  
  80. //********** 게시판 예제에 필요한 객체
  81.     <table>
  82.         <tr><td>신형 넥수스 10 미개봉 팝니다.</td><td>62만원</td></tr>
  83.         <tr><td>갤록시S5 전투용 싸게 처분합니다.</td><td>45만원</td></tr>
  84.         <tr><td>안드로이드 프로그래밍 정복 새 책</td><td>8만원</td></tr>
  85.         <tr><td>ASUS 젬북 UX21A full hd, i7 CPU, RAM 4G, 256 SSD</td><td>99</td></tr>
  86.         <tr><td>2.5인치 샘송 외장하드 1테라. 좋은 자료 겁나 많음</td><td>12만원</td></tr>
  87.         <tr><td>거의 신품급 DSLR. 캐농 750d 듀얼 랜즈</td><td>75만원</td></tr>
  88.         <tr><td>애뿔 아이뽕6 가개통급. 한개 60만원, 두개 130만원</td><td>60만원</td></tr>
  89.         <tr><td>경희대 앞 넓고 깔끔한 원룸. 초역세권에 신축 풀옵션</td><td>500/50</td></tr>
  90.         <tr><td>스타 2. 자유의 날개 + 군단의 심장 합쳐서 떨이합니다.</td><td>30000</td></tr>
  91.     </table>
  92. </body>
  93. </html>


Scenario: JAVA SCRIPT의 DOM 객체를 활용하여 mouse over, out에 따라 움직임는 그림을 표현하고자 하였으나, 

마우스를 올리면, H1의 텍스트나 모두 변했지만, 이상하게 그림만 변하지 않는 것이었다.  firstChild의 개념이 이해가 잘 가지 않았던 

나는, 삽질을 많이하다가, 답을 발견했다.


Solutions : 선생님 왈 "DOM객체를 이용할땐 항상 트리구조를 생각해야된다. 그러므로 띄어쓰기 없이 바로 붙여써줘야됨"


ex) 마우스 over out의 따라 동적으로 변하는 버튼 만들기. 예제 소스

HTML 5 1.10 KB
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>DOM 객체</title>
  6. </head>
  7. <body>
  8.     <h1 id="title">마우스 아웃</h1>
  9.     <a onmouseover="mOver()" onmouseout="mOut()" href="#" id="btn"><img src="https://t1.daumcdn.net/cfile/tistory/227AF044589C1B6110"alt="버튼"/></a>
  10. //항상  트리구조를 생각해야된다. 그러므로 띄어쓰기 없이 바로 붙여써줘야됨
  11.     <p id="img_src"></p>
  12.    
  13. <script>
  14.     //<![CDATA[
  15.  
  16.     var theBtn = document.getElementById("btn");
  17.     var s = document.getElementById("img_src");
  18.  
  19.     //버튼위에 mouseover 되었을때
  20.     function mOver() {
  21.         title.innerHTML = "마우스 오버";
  22.         theBtn.firstChild.src = "https://t1.daumcdn.net/cfile/tistory/247FA346589C1B311E";
  23.         s.innerHTML = theBtn.firstChild.src;
  24.     }
  25.  
  26.     function mOut() {
  27.         title.innerHTML = "마우스 아웃";
  28.         theBtn.firstChild.src = "https://t1.daumcdn.net/cfile/tistory/227AF044589C1B6110";
  29.         s.innerHTML = theBtn.firstChild.src;
  30.  
  31.     }
  32.  
  33.     //버튼위에 mouseout 되었을때(default상태), 추가적으로 버튼주소 추가하여 출력하기
  34.  
  35.     //]]>
  36. </script>
  37. </body>
  38. </html>

ps.실행 결과 (링크로 들어가서 run을 눌러주면 됩니다.)



Javascript Array 의 유용한 메소드들

http://jhjang.egloos.com/2369285

Java 의 Vector 클래스는 내부적으로 배열을 사용하고 있다. 따라서 Vector 의 자바스크립트 버전을 만들기 위해서는 Array 객체에 대한 빵빵한 지식이 필요하다 (없어도 된다. 그러나 있으면 매우 좋다). 자! 배열의 기초와 유용한 메쏘드들을 살펴보자.
배열의 생성

1. 생성자를 이용한 생성

- new Array(arrayLength)

ex) friends = new Array(3); // 크기가 3 인 배열 생성

- new Array(element0, element1, ... , elementN)

ex) friends = new Array("개똥이", "소똥이", "말똥이"); // 크기 3인 배열 생성(값이 채워짐)

2. 직접 생성

friends = ["개똥이", "소똥이", "말똥이"];

간접적인 배열 길이의 증가

배열의 길이는 현재 배열의 길이보다 큰 인덱스를 사용하면 자동으로 증가한다. 아래는 배열의 길이가 0 인 객체 생성 후 99번째 요소에 값을 할당하여 배열의 길이가 100 으로 증가한 예이다.

friends = new Array();

friends[99] = "새똥이";

메쏘드 종류

concat : 두개의 배열을 합쳐 새로운 배열을 리턴한다. 원본 배열은 변하지 않는다.

문법

arrayName.concat(arrayName2, arrayName3, ... , arrayNameN)

인자

arrayName2, ... , arrayNameN - 합쳐질 인자들

예제

두 배열을 합치는 예

alpha = new Array("a", "b", "c");

numeric = new Array(1, 2, 3);

alphaNumeric = alpha.concat(numeric); // ["a", "b", "c", 1, 2, 3] 배열 생성

join : 모든 요소가 구분자로 이어진 문자열을 리턴한다. 디폴트 구분자는 comma(,) 이다.

문법

arrayName.join(separator)

인자

separator 요소와 요소 사이에 사용될 구분자 문자열

예제

friends = new Array("소똥이", "개똥이", "말똥이");

strFriends1 = friends.join(); // 소똥이,개똥이,말똥이

strFriends2 = friends.join(", "); // 소똥이, 개똥이, 말똥이

strFriends3 = friends.join(" + "); // 소똥이 + 개똥이 + 말똥이

pop : 배열의 마지막 요소를 삭제한 후 그 값을 리턴하고 배열의 크기를 줄인다.

문법

arrayName.pop()

인자

없음

예제

// 말똥이가 pop 되고 배열에는 "개똥이", "소똥이"만 남는다.

// 배열크기도 2로 줄어든다.

friends = ["개똥이", "소똥이", "말똥이"];

popped = friends.pop(); // popped 에 말똥이가 할당된다.

push : 배열에 하나 또는 여러개의 값을 넣고 새로운 배열의 길이를 리턴한다.(배열길이 증가)

문법

arrayName.push(element1, element2, ... , elementN)

인자

element1, element2, ... , elementN - 추가될 요소들

예제

friends = ["개똥이", "소똥이"];

pushed = friends.push("말똥이", "새똥이"); // ["개똥이", "소똥이", "말똥이", "새똥이"]

alert(pushed); // 4

reverse : 배열 요소를 역순으로 재배치한다(첫번째 요소는 마지막으로, 마지막 요소는 처음으로).

문법

arrayName.reverse()

인자

없음

예제

myArray = new Array("1", "2", "3");

myArray.reverse(); // ["3", "2", "1"]

shift : 첫번째 요소를 삭제하고 배열의 길이를 하나 줄인 후, 삭제된 요소를 리턴한다.

문법

arrayName.shift()

인자

없음

예제

friends = ["개똥이", "소똥이", "말똥이"];

shifted = friends.shift(); // ["소똥이", "말똥이"]

alert("삭제된 요소는 " + shifted + " 입니다."); // 개똥이

slice : 얇게 썬 슬라이스 치즈가 생각난다(^^). 배열의 일부를 잘라내어 새로운 배열을 리턴한다.

문법

arrayName.slice(begin[,end]) : [] 은 선택사항임

인자

begin - 0보다 큰 시작 인덱스 (필수)

end - 0보다 큰 끝 인덱스 (선택). 지정되지 않으면 배열의 끝까지 복사된다.

예제

numbers = ["0", "1", "2", "3", "4"];

sliced1 = numbers.slice(2, 3); // ["2"]

sliced2 = numbers.slice(2); // ["2", "3", "4"]

sort : 배열의 요소를 정렬한다.

문법

arrayName.sort([compareFunction])

인자

compareFunction - 정렬방법을 지정한 함수.

생략시에는 요소들의 toString() 값을 사전순서(Dictionary order) 대로 정렬한다.

compareFunction(a, b) 에서

1) a > b : 0 보다 큰 값 리턴

2) a = b : 0 리턴

3) a < b : 0 보다 작은 값 리턴

예제

// 역행 정렬

function descComparator(a, b) {

return b - a;

}

// 순행 정렬

function ascComparator(a, b) {

return a - b;

}

numbers = ["0", "1", "2", "3", "4"];

numbers.sort(); // ["1", "2", "3", "4", "5"]

numbers.sort(ascComparator); // ["1", "2", "3", "4", "5"]

numbers.sort(descComparator); // ["4", "3", "2", "1", "0"]

splice : 이전 배열요소를 삭제하고 새로운 내용물을 추가하는 형태로 배열 내용을 변경한다. 삭제된 요소들은 리턴된다. Vector 와 유사한 기능을 하므로 숙지하자.

문법

arrayName.splice(index, howMany, [element1][, ..., elementN])

인자

index - 변경하고자 하는 요소의 시작 인덱스

howMany - 삭제하고자 하는 이전 배열요소 갯수.

element,...,elementN - 추가하고자 하는 배열 요소들

예제

// numbers[2]부터 2개("2", "3")를 삭제하고 그 자리에 "5"와 "6" 을 삽입한다.

numbers = ["0", "1", "2", "3", "4"];

spliced = numbers.splice(2, 2, "5", "6"); // ["0", "1", "5""6", "4"]

alert(spliced); // "2", "3"

unshift : 하나 또는 여러개의 요소를 배열의 왼쪽에 추가한다. 배열길이는 증가한다.

문법

arrayName.unshift(element1,..., elementN)

인자

element1,...,elementN - 배열의 앞쪽에 들어갈 요소들

예제

numbers = ["0", "1", "2"];

numbers.unshift("-2", "-1"); // ["-2", "-1", "0", "1", "2"]

*by 라셍, 문제시 삭제하겠습니다.

Scenario: JavaScript 학습도중, 계산기를 만들어보고자함


Solution: 하다보니 가장 막혔던 부분은, form태그의 name 속성 이었다. 원래는 action이나 id 속성만 줘봤는데,

 폼 테그에 text를 접근하려면 Form에 Name을 부여해서 접근할 수 있어야됨.




Ex: 완성 예시(링크 접근후 Runs 클릭)

http://www.w3schools.com/code/tryit.asp?filename=FCHYBFKWWWPO



  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Calculation</title>
  6. <style>
  7. legend {
  8. }
  9. p{
  10.     height: 20px;
  11. }
  12. fieldset{
  13.     width: 150px;
  14. }
  15.  
  16. #calc {
  17. }
  18.  
  19. #calc input[type=button] {
  20.     border: thin 1px ;
  21.     width: 25px;
  22.     text-align: center;
  23.     border-color:  #1ad1ff;
  24. }
  25.  
  26. #win {
  27.     width: 145px;
  28.     background-color: #b3f0ff;
  29.     border: none;
  30. }
  31. </style>
  32. <script>
  33. function cal(num){
  34.     myform.win.value += num;
  35.     console.log(num);
  36. }  
  37.  
  38. function answer(){
  39.     try{
  40.         myform.win.value = eval(document.myform.win.value);
  41.     }catch(e){alert('잘못된 연산오류 ㅋ')}
  42. }
  43.  
  44. function clearcal(){
  45.     myform.win.value = "";
  46. }
  47.  
  48. </script>
  49. </head>
  50. <body>
  51. <!--    맨처음에 폼테그는 무조건 action만 써봐서 착각함, 이곳에 네임속성을써줘야 자바스크립트에서 텍스트뷰에 값입력해줌 -->
  52.     <form name="myform" id="calc">
  53.         <fieldset >
  54.             <p><input type="text" id="win"> </p>
  55.            
  56.             <p>
  57.             <input type="button" value="1" onclick="cal('1')">
  58.             <input type="button" value="2" onclick="cal('2')">
  59.             <input type="button" value="3" onclick="cal('3')">
  60.             <input type="button" value="4" onclick="cal('4')">
  61.             <input type="button" value="5" onclick="cal('5')">
  62.             </p>
  63.             <p>
  64.             <input type="button" value="6" onclick="cal('6')">
  65.             <input type="button" value="7" onclick="cal('7')">
  66.             <input type="button" value="8" onclick="cal('8')">
  67.             <input type="button" value="9" onclick="cal('9')">
  68.             <input type="button" value="0" onclick="cal('10')">
  69.             </p>
  70.             <p>
  71.             <input type="button" value="/" onclick="cal('/')">
  72.             <input type="button" value="*" onclick="cal('*')">
  73.             <input type="button" value="-" onclick="cal('-')">
  74.             <input type="button" value="+" onclick="cal('+')">
  75.             <input type="button" value="=" onclick="answer()">
  76.             </p>
  77.             <p>
  78.             <input type="button" value="C" onclick="clearcal()">
  79.             </p>
  80.         </fieldset>
  81.     </form>
  82. </body>
  83. </html>




+ Recent posts