Build CRUD Application with jQuery EasyUI

Tutorial » Build CRUD Application with jQuery EasyUI

It has become a common necessily for web application to collect data and manage it properly. CRUD allows us to generate pages to list and edit database records. This tutorial will show you how to implement a CRUD DataGrid using jQuery EasyUI framework.

We will use following plugins:

  • datagrid: show the user list data.
  • dialog: create or edit a single user information.
  • form: used to submit form data.
  • messager: to show some operation messages.

Step 1: Prepare database

We will use MySql database to store user information. Create database and 'users' table.

Step 2: Create DataGrid to display user information

Create the DataGrid with no javascript code.

  1. <table id="dg" title="My Users" class="easyui-datagrid" style="width:550px;height:250px"  
  2.         url="get_users.php"  
  3.         toolbar="#toolbar"  
  4.         rownumbers="true" fitColumns="true" singleSelect="true">  
  5.     <thead>  
  6.         <tr>  
  7.             <th field="firstname" width="50">First Name</th>  
  8.             <th field="lastname" width="50">Last Name</th>  
  9.             <th field="phone" width="50">Phone</th>  
  10.             <th field="email" width="50">Email</th>  
  11.         </tr>  
  12.     </thead>  
  13. </table>  
  14. <div id="toolbar">  
  15.     <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>  
  16.     <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>  
  17.     <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">Remove User</a>  
  18. </div>  

We don't need to write any javascript code and we can show the user list as following image:

The DataGrid use the 'url' property that is assigned to 'get_users.php' to retrieve data from server.

Code of get_users.php file

  1. $rs = mysql_query('select * from users');  
  2. $result = array();  
  3. while($row = mysql_fetch_object($rs)){  
  4.     array_push($result, $row);  
  5. }  
  6.   
  7. echo json_encode($result);  

Step 3: Create form dialog

To create or edit a user, we use the same dialog.

  1. <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"  
  2.         closed="true" buttons="#dlg-buttons">  
  3.     <div class="ftitle">User Information</div>  
  4.     <form id="fm" method="post">  
  5.         <div class="fitem">  
  6.             <label>First Name:</label>  
  7.             <input name="firstname" class="easyui-validatebox" required="true">  
  8.         </div>  
  9.         <div class="fitem">  
  10.             <label>Last Name:</label>  
  11.             <input name="lastname" class="easyui-validatebox" required="true">  
  12.         </div>  
  13.         <div class="fitem">  
  14.             <label>Phone:</label>  
  15.             <input name="phone">  
  16.         </div>  
  17.         <div class="fitem">  
  18.             <label>Email:</label>  
  19.             <input name="email" class="easyui-validatebox" validType="email">  
  20.         </div>  
  21.     </form>  
  22. </div>  
  23. <div id="dlg-buttons">  
  24.     <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a>  
  25.     <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">Cancel</a>  
  26. </div>  

The dialog is created with no javascript code also.

Step 4: Implement creating and editing a user

When create a user, we open the dialog and clear form data.

  1. function newUser(){  
  2.     $('#dlg').dialog('open').dialog('setTitle','New User');  
  3.     $('#fm').form('clear');  
  4.     url = 'save_user.php';  
  5. }  

When edit a user, we open the dialog and load form data from the selected datagrid row.

  1. var row = $('#dg').datagrid('getSelected');  
  2. if (row){  
  3.     $('#dlg').dialog('open').dialog('setTitle','Edit User');  
  4.     $('#fm').form('load',row);  
  5.     url = 'update_user.php?id='+row.id;  
  6. }  

The 'url' stores the URL address where the form will post to when save the user data.

Step 5: Save the user data

To save the user data we use the following code:

  1. function saveUser(){  
  2.     $('#fm').form('submit',{  
  3.         url: url,  
  4.         onSubmit: function(){  
  5.             return $(this).form('validate');  
  6.         },  
  7.         success: function(result){  
  8.             var result = eval('('+result+')');  
  9.             if (result.success){  
  10.                 $('#dlg').dialog('close');      // close the dialog  
  11.                 $('#dg').datagrid('reload');    // reload the user data  
  12.             } else {  
  13.                 $.messager.show({  
  14.                     title: 'Error',  
  15.                     msg: result.msg  
  16.                 });  
  17.             }  
  18.         }  
  19.     });  
  20. }  

Before submit the form, the 'onSubmit' function will be called, in which we can validate the form field value. When the form field values are submited successfully, close the dialog and reload the datagrid data.

Step 6: Remove a user

To remove a user, we use the following code:

  1. function removeUser(){  
  2.     var row = $('#dg').datagrid('getSelected');  
  3.     if (row){  
  4.         $.messager.confirm('Confirm','Are you sure you want to remove this user?',function(r){  
  5.             if (r){  
  6.                 $.post('remove_user.php',{id:row.id},function(result){  
  7.                     if (result.success){  
  8.                         $('#dg').datagrid('reload');    // reload the user data  
  9.                     } else {  
  10.                         $.messager.show({   // show error message  
  11.                             title: 'Error',  
  12.                             msg: result.msg  
  13.                         });  
  14.                     }  
  15.                 },'json');  
  16.             }  
  17.         });  
  18.     }  
  19. }  

Before remove a row, we will display a confirm dialog to let user to determine whether to really remove the row data. When remove data successfully, call 'reload' method to refresh the datagrid data.

Step 7: Run the Code

Run the code in your browser with MySQL started.

So, you now know the basics of CRUD in jQuery EasyUI framework. Press below link to start the demo application.

Download the EasyUI example:


'J-Query' 카테고리의 다른 글

jQuey eq form 값 반디 모음 1  (0) 2012.06.22
select 태그에서 선택된 option 값 알아보기  (1) 2012.06.15
슬라이드 시계  (0) 2012.06.13
JQuery 시계  (0) 2012.06.13
조작하려는 엘리먼트 선택하기  (0) 2012.06.07
Posted by 사라링

슬라이드 시계

2012. 6. 13. 09:31


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>jQuery Sliding Clock v1.1</title> <style type="text/css"> body { background:#bae1ea url(back.jpg) 50% 0px no-repeat; color:#000; } /* container for clock */ #wrap { position:relative; margin: 100px auto 0; width:700px; height:440px; background:url("slider clock(trans).png") no-repeat top left;
border-style:solid; border-width:1px; overflow:hidden; } /* style background and size of all sliding divs */ #wrap div { position:absolute; margin-left:-700px; width:1400px; height:40px; background:url("slider clock(trans).png") repeat-x; } /* specific position and background position for sliding divs */ #wrap #day { top:40px; background-position:0 -440px; } #wrap #month { top:120px; background-position:0 -480px; } #wrap #date { top:200px; background-position:0 -520px; } #wrap #hour { top:280px; background-position:0 -560px; } #wrap #min { top:320px; background-position:0 -600px; } #wrap #sec { top:400px; background-position:0 -640px; } #title { margin:20px auto; width:550px; text-align:center; } #other { margin:10px auto; width:550px; text-align:center; }
</style> <script type="text/javascript" src="jquery.js"> </script> <script> $(document).ready(function(){ function checktime(olddel){ var now = new Date(); var nowdel = now.getDay() + "|" + now.getMonth() + "|" + now.getDate() + "|" + now.getHours() + "|" + now.getMinutes() + "|" + now.getSeconds(); if ( olddel != nowdel ) { var oldsplit = olddel.split("|"); var nowsplit = nowdel.split("|"); if ( oldsplit[5] != nowsplit[5] ) { clock_slide('#sec',nowsplit[5],11); if ( oldsplit[4] != nowsplit[4] ) { clock_slide('#min',nowsplit[4],11); if ( oldsplit[3] != nowsplit[3] ) { clock_slide('#hour',nowsplit[3],28); if ( oldsplit[2] != nowsplit[2] ) { clock_slide('#day',nowsplit[0],100); clock_slide('#date',(nowsplit[2]-1),22); if ( oldsplit[1] != nowsplit[1] ) { clock_slide('#month',nowsplit[1],57); }; }; }; }; }; }; function clock_slide(which,howmuch,multiple){ $(which).stop().animate({marginLeft: ((howmuch*multiple)-700)+'px'}, 250, 'linear'); }; setTimeout(function(){checktime(nowdel);}, 250); }; checktime("0|0|0|0|0|0"); }); </script> </head> <body> <div id="wrap"> <div id="day"> </div> <div id="month"> </div> <div id="date"> </div> <div id="hour"> </div> <div id="min"> </div> <div id="sec"> </div> </div> <!-- End "wrap" --> <div id="title">jQuery transpearant Slider clock with CSS sprites - by <a href="http://doodleaday.wordpress.com">vonholdt</a></div> <div id="other">Check out my other jQuery clock <a href="http://home.comcast.net/~vonholdt/test/clock/index.htm">here</a></div> </body> </html>

출처 : http://home.comcast.net/~vonholdt/test/clock_slide/index.htm

Posted by 사라링

JQuery 시계

2012. 6. 13. 09:23

jDigiClock

Digital Clock (HTC Hero inspired)

Author: Radoslav Dimov
Version: 2.1 (Changelog)
Download: jdigiclock.zip
Licence: Dual licensed under the MIT and GPL licenses.

Contents

  1. Introduction
  2. Examples
  3. Getting started
  4. Configuration
  5. Compatibility

Introduction

jDigiClock is a jQuery plugin inspired from HTC Hero Clock Widget.

Examples

Bourgas

Clear

Wed, 13 Jun

20°C

20°C

33° / 19°

Bourgas

Sunny and hot

  • Thu

    Warm and humid with some sun

    31° / 17°

  • Fri

    Sunny and humid

    28° / 17°

  • Sat

    Sunny and nice

    26° / 14°

  • Sun

    Sunny and nice

    27° / 14°

reloadWed, 13 Jun, 09:20


Getting started

To use the jDigiClock plugin, include the jQuery library, the jDigiClock source file and jDigiClock core stylesheet file inside the <head> tag of your HTML document:

<link rel="stylesheet" type="text/css" href="css/jquery.jdigiclock.css" />
<script type="text/javascript" src="lib/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="lib/jquery.jdigiclock.js"></script>

To setup jDigiClock, add the following code inside the <head> tag of your HTML document:

<script type="text/javascript">
    $(document).ready(function() {
        $('#digiclock').jdigiclock({
            // Configuration goes here
        });
    });
</script>

jDigiClock accepts a lot of configuration options, see chapter "Configuration" for further informations.

jDigiClock expects a very basic HTML markup structure inside your HTML document:

<div id="digiclock"></div>

Configuration

jDigiClock accepts a list of options to control the appearance and behaviour of the Digital Clock. Here is the list of options you may set:

Property Type Default Description
clockImagesPath string "images/clock/" Clock images path.
weatherImagesPath string "images/weather/" Weather images path.
am_pm boolean false Specifies the AM/PM option.
weatherLocationCode string "EUR|BG|BU002|BOURGAS" Weather location code (see: WeatherLocationDatabase.txt).
weatherMetric string "C" Specifies the weather metric mode: C or F.
weatherUpdate integer 0 Weather update in minutes.
proxyType string "php" Specifies proxy type: php or asp (see: README.txt).

Compatibility

jDigiClock has been tested and works on the following browsers:

  • Internet Explorer 7 (PC)
  • FireFox 3.5 (PC/Linux)
  • Google Chrome 3.0 (PC)
  • Safari 4.0 (PC)

Donate a beer or two via PayPal


'J-Query' 카테고리의 다른 글

Build CRUD Application with jQuery EasyUI  (0) 2012.06.14
슬라이드 시계  (0) 2012.06.13
조작하려는 엘리먼트 선택하기  (0) 2012.06.07
버튼이벤트->레이어 새창으로 표현  (0) 2012.05.08
list 추출및 select 구현  (0) 2012.05.08
Posted by 사라링

조작하려는 엘리먼트 선택하기

jQuery 2011/06/20 11:23

조작하려는 엘리먼트 선택하기

전 장에서도 간단히 살펴보았지만 우선 jQuery매소드를 사용하기 위해선 페이지에서 조작할 엘리먼트를 선택해야 한다. 여기선 이런 엘리먼트를 선택하는 방법에 대해 알아보자.
  • 기본 CSS 선택자를 이용해 선택하기
  • 위치로 선택하기
  • jQuery 정의 선택자로 선택하기
위의 세가지 방법을 이용해 엘리먼트를 선택하는 것에 대해 알아보자.

기본 CSS 선택자 사용하기

CSS를 사용해 본 유저라면 이 선택 기법은 익숙할 것이다.엘리먼트의 ID, CSS 클래스명, 태그명, 페이지 엘리먼트의 DOM 계층 구조를 이용해 엘리먼트를 선택하는 기법이 그것들이며 아래의 예를 보자.
  • a - 모든 링크 엘리먼트와 일치하는 선택자
  • #specialID - specialID를 아이디로 가지는 엘리먼트와 일치하는 선택자
  • .specialClass - specialClass를 클래스로 가지는 모든 엘리먼트와 일치하는 선택자
  • a#specialID.specialClass - 아이디가 specialID이고 specialClass를 클래스로 가지는 링크와 일치하는 선택자
  • p a.specialClass - 단락 엘리먼트 내에 선언되고 specialClass를 클래스로 가지는 모든 링크와 일치하는 선택자
이러한 기존의 CSS 선택자를 이용하여 엘리먼트를 선택할 수 있게 되는데, jQuery가 지원하는 선택자들은 아래와 같다.
선택자내 용
*모든 엘리먼트
E태그명이 E인 모든 엘리먼트
E FE의 자손이면서 태그명이 F인 모든 엘리먼트
E>FE의 바로 아래 자식이면서 태그명이 F인 모든 엘리먼트
E+FE의 형제 엘리먼트로 바로 다음에 나오는 엘리먼트 F
E~FE의 형제 엘리먼트로 다음에 나오는 모든 엘리먼트 F
E:has(F)태그명이 F인 자손을 하나 이상 가지는 태그명이 E인 모든 엘리먼트
E.C클래스명 C를 가지는 모든 엘리먼트 E
E#I아이디가 I인 엘리먼트 E
E[A]속성 A를 가지는 모든 엘리먼트 E
E[A=V]값이 V인 속성 A를 가지는 모든 엘리먼트 E
E[A^=V]값이 V로 시작하는 속성 A를 가지는 모든 엘리먼트 E
E[A$=V]값이 V로 끝나는 속성 A를 가지는 모든 엘리먼트 E
E[A*=V]값이 V를 포함하는 속성 A를 가지는 모든 엘리먼트 E
위의 선택자를 활용하는 방법에 대해 예제를 통해 알아보자.(예제보기)

위치로 선택하기

때로는 페이지에 있는 엘리먼트 위치나 다른 엘리먼트와 연관된 관계를 기반으로 엘리먼트를 선택해야 한다. 예를 들어 페이지에서 첫 번째 링크나 홀수 및 짝수 번째 문단 등을 선택하는 기법이 필요할 때가 있다. 이에 대해 정리한 것이 아래의 표이다.
선택자설 명
:first페이지에서 처음으로 일치하는 엘리먼트
:last페이제에서 마지막으로 일치하는 엘리먼트
:first-child첫 번째 자식 엘리먼트
:last-child마지막 자식 엘리먼트
:only-child형제가 없는 모든 엘리먼트를 반환
:nth-child(n)n번째 자식 엘리먼트
:nth-child(even|odd)짝수 혹은 홀수 자식 엘리먼트
:nth-child(Xn+Y)전달된 공식에 따른 n번째 자식 엘리먼트
:even / :odd페이지 전체의 짝수/홀수 엘리먼트
:eq(n)n번째로 일치하는 엘리먼트
:gt(n)n번째 엘리먼트 이후의 엘리먼트와 일치
:lt(n)n번째 엘리먼트 이전의 엘리먼트와 일치

jQuery 정의 선택자 사용하기

CSS 선택자를 이용해 우리는 원하는 DOM 엘리먼트를 선택할 수 있었지만 때로는 이것만으로 표현할 수 없는 특성이 있는 엘리먼트를 선택해야 한다. 예를 들어 라디어 버튼 중 check가 된 엘리먼트만을 선택하기에는 CSS선택자만으로는 부족하다. 이렇듯 부족한 부분을 jQuery 정의 선택자를 이용하여 채울 수 있다.
선택자설 명
:animated현재 애니메이션이 적용되고 있는 엘리먼트
:button모든 버튼을 선택
:checkbox체크박스 엘리먼트 선택
:checked선택된 체크박스나 라디오 버튼을 선택
:contains(foo)텍스트 foo를 포함하는 엘리먼트 선택
:disabled인터페이스에서 비활성화 상태인 모든 폼 엘리먼트를 선택
:enabled인터페이스에서 활성화 상태인 모든 폼 엘리먼트를 선택
:file모든 파일 엘리먼트를 선택
:header헤더 엘리먼트 선택
:hidden감춰진 엘리먼트 선택
:image폼 이미지를 선택
:input폼 엘리먼트만 선택
:not(filter)필터의 값을 반대로 변경
:parent빈 엘리먼트를 제외하고, 텍스트도 포함해서 자식 엘리먼트를 가지는 엘리먼트
:password패스워드 엘리먼트 선택
:radio라디오 버튼 엘리먼트 선택
:reset리셋 버튼을 선택
:selected선택된 엘리먼트 선택
:submit전송 버튼을 선택
:text텍스트 엘리먼트 선택
:visible보이는 엘리먼트 선택
여러 jQuery 정의 선택자가 폼과 관련되며 덕분에 특정 엘리먼트의 타입이나 상태를 세련되게 표현할 수 있다. 선택자 필터도 조합할 수 있다. 예를 들어 활성화 되고 선택된 체크박스만 일치시키려 한다면 다음과 같다.
 
 
:checkbox:checked:enabled

새로운 HTML 생성하기

jQuery() 함수는 페이지의 엘리먼트를 선택할 뿐 아니라 새로운 HTML을 생성할 수도 있다.
 
$("<div>안녕</div>")
이 표현식은 페이지에 추가할 새로운 <div> 엘리먼트를 생성한다. 다음의 코드를 이용하여 <div> 엘리먼트를 두 개 생성해보자.
 

$("<div class='foo'>내가 foo를 가졌다.</div><div>나는 foo를 가지지 않았다.")

.filter(".foo").click(function(){ alert("내가 foo이다."); })

.end().appendTo("#someParentDiv");

위의 코드는 <div> 엘리먼트를 생성하는데 첫번째 <div> 엘리먼트는 foo 클래스가 있고, 다른 하나에는 없다. 생성한 첫번째 <div> 엘리먼트를 클릭하면 alert()가 실행된다. 마지막으로 end()메서드를 이용해 필터링 이전의 두 <div>엘리먼트를 지닌 집합으로 돌아간 뒤, 이 집합을 id가 someParentDiv인 엘리먼트에 덧붙인다.


'J-Query' 카테고리의 다른 글

슬라이드 시계  (0) 2012.06.13
JQuery 시계  (0) 2012.06.13
버튼이벤트->레이어 새창으로 표현  (0) 2012.05.08
list 추출및 select 구현  (0) 2012.05.08
9일차 XML문서  (0) 2012.05.08
Posted by 사라링


화면은 아래와 같이 표현되며 구글라이브러리 jQuery API 인 js 파일을

상단에 링크해준다. 그리고 Style 을 원하는 형태로 정한뒤 폼레이어에

적용하자.


소스

<html>

<head>

<title>Untitled Document</title>

<meta
http-equiv="Content-Type"
content="text/html; charset=euc-kr">

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

<!-- Style 선언 -->

<style
type="text/css">

#divLangSelect {

position:absolute;

display:none;

background-color:#FFCC00;

border:solid 2px #d0d0d0;

width:350px;

height:150px;

padding:10px;

}

</style>

<!-- //Style 선언 -->

</head>

<body>

<!-- 버튼이미지 -->

<img
src='1286960090_home.png'
alt="
버튼1"
width="48"
height="48"
class='imgSelect'
/>

<img
src='synchronize48.png'
alt="
버튼2"
width="48"
height="48"
class='imgSelect'
/>

<img
src='1286960551_yahoo-buzz-logo-square2.png'
alt="
버튼3"
width="40"
height="40"
class='imgSelect'
/>

<!-- //버튼이미지 -->


<!-- 레이어-->

<div
id="divLangSelect">

<div
style="position:absolute;top:5px;right:5px">

<span
onClick="javascript:document.getElementById('divLangSelect').style.display='none'"style="cursor:pointer;font-size:1.5em" title="
닫기">X</span>

</div>표현하고자하는내용을넣으면된다. 오른쪽엔닫기버튼이다. 적당한아이콘넣어서

이쁘게표현해보자.

</div>

<!-- //레이어-->

 

<script
type="text/javascript">

//-- 버튼클릭시버튼을클릭한위치근처에레이어생성 --//

$('.imgSelect').click(function(e) {

var divTop = e.clientY + 10; //상단좌표

var divLeft = e.clientX + 10; //좌측좌표

$('#divLangSelect').css({

"top": divTop

,"left": divLeft

, "position": "absolute"

}).show();

});

</script>

 

</body>

</html>

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

JQuery 시계  (0) 2012.06.13
조작하려는 엘리먼트 선택하기  (0) 2012.06.07
list 추출및 select 구현  (0) 2012.05.08
9일차 XML문서  (0) 2012.05.08
8일차 사용자정의객체&JSON표기법  (0) 2012.05.08
Posted by 사라링

list 추출및 select 구현

2012. 5. 8. 18:25

결과물

DAOmybatis_00000.jpg

   테이블 선택시

 

DAOmybatis_00000_00000.jpg

 

소스 / /

 

memberinfo.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>memberInfo.html::김훈</title>
        <script type="text/javascript" src="../../js/jquery-1.7.2.js">
        </script>
        <script type="text/javascript">
            $(function(){
                $.getJSON("memberData.jsp",
                     function(data){
                  //  alert(data);
                    var str = "<table id='mem_list' align='center'border='1' bordercolor='yellow' >";
                    str += "<tr bgcolor='silver'><th>회원ID</th><th>회원성명</th><th>주민번호</th><th>우편번호</th>";
                    str +="<th>주 소</th><th>회사전화</th><th>핸드폰</th><th>이메일</th></tr>";
                    $.each(data, function(i, v){
                        str += "<tr id='mem_select'>";
                        str += "<td class='mem_id'>" + v.mem_id + "</td>";
                        str += "<td>" + v.mem_name + "</td>";
                        str += "<td>" + v.mem_regno + "</td>";
                        str += "<td>" + v.mem_zip + "</td>";
                        str += "<td>" + v.mem_add + "</td>";
                        str += "<td>" + v.mem_comtel + "</td>";
                        str += "<td>" + v.mem_hp + "</td>";
                        str += "<td>" + v.mem_mail + "</td></tr>";
                    });
                    str += "</table>";
                    $("#memList").html(str);
                });
                $("#mem_select").live("click", function(){
                    var mem_id = $(this).children(".mem_id").text().trim();
                    $.getJSON("memberData.jsp",
                     "mem_id="+mem_id,
                      function(data){
                          $.each(data,function(i,v){
                        $("#mem_id").val(v.mem_id);
                        $("#mem_pass").val(v.mem_pass);
                        $("#mem_name").val(v.mem_name);
                        $("#mem_regno").val(v.mem_regno);
                        $("#mem_bir").val(v.mem_bir);
                        $("#mem_zip").val(v.mem_zip);
                        $("#mem_add").val(v.mem_add);
                        $("#mem_hometel").val(v.mem_hometel);
                        $("#mem_comtel").val(v.mem_comtel);
                        $("#mem_hp").val(v.mem_hp);
                        $("#mem_mail").val(v.mem_mail);
                        $("#mem_job").val(v.mem_job);
                        $("#mem_like").val(v.mem_like);
                        $("#mem_memorial").val(v.mem_memorial);
                        $("#mem_memorialday").val(v.mem_memorialday);
                        $("#mem_mileage").val(v.mem_mileage);
                        if (v.mem_delete != "y") {
                            $("#mem_delete").attr("checked", true);
                        }
                        });
                    });
                   
                });
               
            });
        </script>
    </head>
    <body>
        <center>
            <table id="memInfo">
                <tr>
                    <td width="400px" align="left">
                        &nbsp;&nbsp;<b>I &nbsp; D : </b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size="20" id="mem_id" disabled="false" />
                    </td>
                    <td width="30px">
                    </td>
                    <td align="left">
                        <b>암  호 : </b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size="20" id="mem_pass" disabled="false" />
                    </td>
                </tr>
                <tr>
                    <td width="400px" align="left">
                        <b>성 &nbsp; 명 : </b>&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size="20" id="mem_name" disabled="false" />
                    </td>
                    <td>
                    </td>
                    <td align="left">
                        <b>주민번호 : </b>
                        <input type="text" size="15" id="mem_regno" disabled="false" />
                    </td>
                </tr>
                <tr>
                    <td width="400px" align="left">
                        <b>생년월일 : </b>
                        <input type="text" size="20" id="mem_bir" disabled="false" />
                    </td>
                    <td>
                        <td colspan="3" align="left">
                            <b>우편번호 : </b>
                            <input type="text" size="7" id="mem_zip" disabled="false" />             
                        </td>
                    </td>
                </tr>
                <tr>
                    <td colspan="3" align="left">
                        <b>주  소 : </b>
                        <input type="text" size="53" id="mem_add" disabled="false" />
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <b>집 전 화 : </b>
                        <input type="text" size="20" id="mem_hometel" disabled="false" />
                    </td>
                    <td>
                    </td>
                    <td align="left">
                        <b>회사전화 :</b>
                        <input type="text" size="20" id="mem_comtel" disabled="false"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <b>핸 드 폰 :</b>
                        <input type="text" size="20" id="mem_hp" disabled="false" />
                    </td>
                    <td>
                    </td>
                    <td align="left">
                        <b>이 메 일 :</b>&nbsp;&nbsp;&nbsp;<input type="text" size="20" id="mem_mail" disabled="false"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <b>직 업 :</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size="20" id="mem_job" disabled="false" />
                    </td>
                    <td>
                    </td>
                    <td align="left">
                        <b>취 미 :</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size="20" id="mem_like" disabled="false" />
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <b>기념일종류 :</b>
                        <input type="text" size="20" id="mem_memorial" disabled="false" />
                    </td>
                    <td>
                    </td>
                    <td align="left">
                        <b>기념일날짜 :</b>
                        <input type="text" size="20" id="mem_memorialday" disabled="false" />
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <b>마일리지 :</b>
                        <input type="text" size="20" id="mem_mileage" disabled="false"/>
                    </td>
                    <td>
                    </td>
                    <td align="left">
                        <b>탈퇴여부 :</b>
                        <input type="checkbox" size="20" id="mem_delete" disabled="false" />
                    </td>
                </tr>
            </table><hr/>
            <div id="memList">
            </div>
        </center>
    </body>
</html>

jsonData.jsp

<%@ page language="java" contentType="text/plain; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="kr.or.ddit.db.ConnectionProvider"%>
<%@page import="java.sql.Connection"%>
<%@ page import = "kr.or.ddit.db.*" %>
<% request.setCharacterEncoding("UTF-8");
    String mem_id=request.getParameter("mem_id");
    System.out.print(mem_id);
%>   
[

<%
    Connection conn = null;
    PreparedStatement psmt = null;;
    ResultSet rs = null;
   
    try{
    conn =ConnectionProvider.getConnection();
   
    if(mem_id==null){
    psmt = conn.prepareStatement("select * from member");
    }else {
    psmt = conn.prepareStatement("select * from member where mem_id=?");
        psmt.setString(1, mem_id);
    }
    rs=psmt.executeQuery();
   
    %>
   
   
    <%
    while(rs.next()){
       
        if(rs.getRow()>1){
            out.print(",");
        }
    %>
    {
    "mem_id"  : "<%=Util.toJS(rs.getString("mem_id"))%>",
    "mem_pass"  : "<%=Util.toJS(rs.getString("mem_pass"))%>",
    "mem_name"  : "<%=Util.toJS(rs.getString("mem_name"))%>",
    "mem_regno"  : "<%=Util.toJS(rs.getString("mem_regno1"))%> - <%=Util.toJS(rs.getString("mem_regno2"))%>",
    "mem_bir"  : "<%=Util.toJS(rs.getString("mem_bir")).subSequence(0, 10)%>",
    "mem_zip"  : "<%=Util.toJS( rs.getString("mem_zip"))%>",
    "mem_add"  : "<%=Util.toJS(rs.getString("mem_add1"))%> <%=Util.toJS(rs.getString("mem_add2"))%>",
    "mem_hometel"  : "<%=Util.toJS(rs.getString("mem_hometel"))%>",
    "mem_comtel"  : "<%=Util.toJS(rs.getString("mem_comtel"))%>",
    "mem_hp"  : "<%=Util.toJS(rs.getString("mem_hp"))%>",
    "mem_mail"  : "<%=Util.toJS(rs.getString("mem_mail"))%>",
    "mem_job"  : "<%=Util.toJS(rs.getString("mem_job"))%>",
    "mem_like"  : "<%=Util.toJS(rs.getString("mem_like"))%>",
    "mem_memorial"  : "<%=Util.toJS(rs.getString("mem_memorial"))%>",
    "mem_memorialday"  : "<%=Util.toJS(rs.getString("mem_memorialday")).subSequence(0, 10)%>",
    "mem_mileage"  : "<%=Util.toJS(rs.getString("mem_mileage"))%>",
    "mem_delete"  : "<%=Util.toJS(rs.getString("mem_delete"))%>"
    }
    <%
    }
    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        if(rs!=null) try{rs.close();}catch(Exception e){}
        if(psmt!=null) try{psmt.close();}catch(Exception e){}
        if(conn!=null) try{conn.close();}catch(Exception e){}
   
    }

%>
]

이 글은 스프링노트에서 작성되었습니다.


'J-Query' 카테고리의 다른 글

조작하려는 엘리먼트 선택하기  (0) 2012.06.07
버튼이벤트->레이어 새창으로 표현  (0) 2012.05.08
9일차 XML문서  (0) 2012.05.08
8일차 사용자정의객체&JSON표기법  (0) 2012.05.08
7일차 Effects  (0) 2012.05.08
Posted by 사라링

9일차 XML문서

2012. 5. 8. 18:25

XML 문서

1.xml 문서의 구조

1) 서두 부분 ==> XML 선언 , PI(Process Instruction)

문서 유형 선언으로 이루어져 있다.

2) 엘리멘트 부분   = >  한 개의 루트엘리먼트가 반드시 있어야 한다.

       그 루트엘리먼트의 자식(하위) 엘리먼트들을 구성하여 문서를 완성한다.

3) 기타 부분         ==> 주석 , PI, 공백등으로 이루어져 있다.(생략가능)

2. 엘리멘트

1) 구조 ==> '<시작테그명>내용(contents)</종료테그명>' 와 같은 구조로 되어 있다.

                (시작 테그명과 종료 테그명은 같아야 한다)

2) 내용 (contents)   ==> 문자데이터, 엘리멘트 , 공백(빈엘리멘트) 등으로 구성 된다.

3) 빈엘리멘트 ==>  '<시작테그명></종료테그명>'는

'</종료테그명>'와 같이 표현 된다.

 

3. 속성 ==> 엘리멘트의 시작 테그 부분에 기술 하는 부자적인 정보의 표현 방법이다.

        1) 구조 ==> '<시작테그명 속성명 ="속성값" ...> 내용</종료테그명>' 와 같이

                          기술하는데 속성값은 반드시 큰 따옴표(")나 작은따옴표(')로 감싸야 한다.

        2) 같은 이름을 갖는 속성명이 2개 이상 올수 없다.

4. 이름(태그명, 속성명등) 작성 규칙

        1)영문자,한글, 밑줄문자(_) 등으로 문자로 시작 할수 있다.

        2) 두번째 문자부터는 숫자, -, : 등을 사용 할 수 있다.

            ( 단 , ':' 문자는 네임스페이스의 구분자로 사용하기 때문에

                    일반적인 태그명에는 사용하지 않는 것이 좋다. )

5. XML 선언 ===> xml문서의 첫째줄에 기술하는 내용으로 현재 문서가 xml 문서임을 시스템에 알려주는 역활을 한다.       

                          형식) <?xml version ="1.0" encoding="<!--인코딩 방식 -->utf-8" standalone="yes 또는 no" ?>

                          규칙) version 은 생략 불가, encoding의 기본값은 'utf-8'

                                  standalone의 기본값은 'no'

6.빌트인 엔티티 ==> 엘리멘트의 내용으로 문자열이 사용된 때 문자열에 '<' 문자나 '&' 문자 등을 직접 사용 할수 없다. 그래서 이러한 문자를 대신
해서 사용 할수 있는 대체문자를 빌트인 엔티티 라고 한다. 

 

                 &lt;       ==> <

           &gt;      ==> >

           &amp;  ==> &

           &quot;  ==>  "

           &apos; ==>  '

           &nbsp; ==> xml에서는 사용 할수 없다. (&#160; 으로 대체 가능)

  -- 문자를 코드값을 이용하여 나타낼수 있다.

     형식) '&#코드값'       ==> 코드값은 10진수로 나타낸다.

              '&#X 코드값 '  ==>  코드값은 16진수로 나타낸다.

7.CDATA 섹션 ==> '<'나 '&' 처럼 문자열로 직접 사용 할수 없는 문자들도 대체문자를 사용하지 않고 직접 사용할수 있는 영역을 나타 낸다

           형식)                <![CDATA[문자열]]>

주석처리 ==>     '<!-- 주석내용 --> '와 같은 형식으로 사용한다.

 

<?xml version="1.0" encoding="UTF-8"?>
<!--
자신의 이력을 XML 문서로 작성 하시오.

 -->
 <이력서>
     <인적사항 >
         <성함 속성="한글">김훈</성함>
         <성함 속성="한문">金勳</성함>
         <성함 속성="영문">kim hun</성함>
         <생년월일>1984년12월24일</생년월일>
         <나이 속성="만">27</나이>
         <주소 우편번호="301-101">대전시 중구 대흥동 뿌잉뿌잉 500번지</주소>
         <연락처>
             <Home 지역번호="042">273-1234</Home>
             <핸드폰>010-123-1234</핸드폰>
             <E-mail>qqdfdg@tt.com</E-mail>
         </연락처>
     </인적사항>
     <학력사항>
         <학교 종류="고등학교">
             <재학기간>
             <시작>1999년3월5일</시작>
             <종료>2002년2월 20일</종료>
             </재학기간>
             <학교명>대덕인재고등학교</학교명>
            <소재지>대전</소재지>
         </학교>
         <학교 종류="대학교">
             <재학기간>
                 <시작>2002년 3월 5일</시작>
                 <종료>2007년 2월 12일</종료>
             </재학기간>
             <학교명>충남대학교</학교명>
            <전공>컴퓨터공학</전공>
            <소재지>대전</소재지>
            <성적>4.0</성적>
         </학교>
     </학력사항>
     <경력사항>
     <경력>
         <재직기간>
         <시작>2007/03/15</시작>
         <종료>2012/03/30</종료>
         </재직기간>
         <직장명>대저IT(주)</직장명>
         <직위>과장</직위>
         <연봉 단위="만원">3000</연봉>
         <퇴직사유>프로젝트 완료</퇴직사유>
         <업무내용>프로그램 개발(PM)</업무내용>
     </경력>
    
         <경력 분야="CS" 년차="1년">(주)블루콤</경력>
         <경력 분야="CS" 년차="4년">(주)이지오스</경력>
     </경력사항>    
     <자격사항>
         <자격면허>
             <자격증>
                 <자격명>정보처리기사</자격명>
                 <취득일>2011년 4월</취득일>
                 <발급기관>산업인력공단</발급기관>
             </자격증>
             <자격증>
                 <자격명>사무자동화산업기사</자격명>
                 <취득일>2011년 11월</취득일>
                 <발급기관>산업인력공단</발급기관>
             </자격증>
        
         </자격면허>
         <외국어 언어="영어">
             <시험명>토익</시험명>
             <점수>770</점수>
         </외국어>
     </자격사항>
    
     <병역사항>
         <구분>병역필
         </구분>
         <군별>육군</군별>
         <계급>대장</계급>
         <복무기간>
             <시작>04-01</시작>
             <종료>06-01</종료>
         </복무기간>
     </병역사항>
    
    
     <가족사항>
         <가족 관계="아버지">
             <성명>ㄱㅈㅎ</성명>
             <나이>53</나이>
            <직업>공무원</직업>
            <동거여부>여</동거여부>
         </가족>
         <가족 관계="어머니">
             <성명>ㅅㅎㅈ</성명>
             <나이>55</나이>
             <직업>주부</직업>
             <동거여부>여</동거여부>
         </가족>
         <가족 관계="동생"></가족>
             <존재>출가외인</존재>
     </가족사항>
 </이력서>

 

이 글은 스프링노트에서 작성되었습니다.


'J-Query' 카테고리의 다른 글

버튼이벤트->레이어 새창으로 표현  (0) 2012.05.08
list 추출및 select 구현  (0) 2012.05.08
8일차 사용자정의객체&JSON표기법  (0) 2012.05.08
7일차 Effects  (0) 2012.05.08
6일차 Utilities  (0) 2012.05.08
Posted by 사라링

 

사용자 정의 객체  -- 클래스를 작성

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">

//    자바 스크립트의 사용저 정의 객체
   
// -- 클래스를 작성
//    function 클래스명(파라미터변수들...){
//        this.속성명;// 속성 선언만
//        ..
//        this.속성명2 = 값 ;// 속성 선언및 초기화
//        ..
//        this.메서드명 = 실제함수명;
//    }
//   
//    function 실제함수명(파라미터 변수들){
//    처리내용;;
//    ..
//    ..
   
// -- 2. 객체를 만들고 , 사용하기
//var 객체변수1 = new 클래스명(값들...);
//var 객체변수2 = new 클래스명(값들...);

//객체변수1.속성명 = 값;
//객체변수1["속성명"]=값;
//
//객체변수1.메소드명(값들...)
 var Member = function(id, name, juminNo){
  this,id = id;
  this.name = name;
  this.juminNo = juminNo;
 }

 //

 // 클래스에 메소드 추가 (prototype명령을 이용한다.)

 // 속성값을 다른 값으로 변경하는 메소드
 Member.prototype.setValue = function(newId, newName, newJuminNo){
  this,id = newId;
  this.name = newName;
  this.juminNo = newJuminNo;
 }
 
 // 주민번호를 이용 나이를 계산하는 메소드
 Member.prototype.getAge = function(){
  var today = new Date();
  var currYear = today.getFullYear();

  var juminYear = Number( this.juminNo.substring(0,2) );
  var flag = this.juminNo.charAt(7); // 성별자리값 읽기

  if(flag=="1" || flag=="2") { // 1900년대 사람
   juminYear += 1900;
  }else{ // 2000년대 사람
   juminYear += 2000;
  }
 
  return (currYear - juminYear);
 }

 // 속성값을 문자열로 구성하여 반환하는 메소드
 Member.prototype.toString = function(){
  return this.id + "[" + this.name + "]" + this.getAge() + "세";
 }

 //------------------------------------------------------------------------

 // 객체생성 및 사용하기 -------

 var mem = new Member("gildong", "홍길동", "800101-1234567");

 var result = mem.toString();

 alert("변경전 : " + result);

 mem.setValue("jimae", "일지매", "000808-3456789");
 result = mem.toString();
 alert("변경후 : " + result);
 
 // 생성된 객체에 새로운 속성과 메소드 추가 하기
 mem.tel  = "042-3222-5453";
 mem.addr = "대전시 중구 대흥동 500번지 " ;
 mem.display= function(){
     var str = "";
     str +="ID : " +this.id +"\n";
     str +="이름 : " +this.name +"\n";
     str +="주민번호 : " +this.juminNo +"\n";
     str +="전화번호 : " +this.tel +"\n";
     str +="주소 : " +this.addr +"\n";
    alert(str);
 }
 
 mem.display();
 
 var mem2 = new Member("ddit","대덕","770707-121212");
alert(mem2.addr);

 
 
   </script>
</head>
<body>

</body>
</html>

 

오브젝트의 속성 추가

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
    // 객체를 생서한 후 생성도니 객체에 속성과 메소드를 추가 할수 있다.
   
    // Object() => 빈 객체를 만들어 준다.
   
    var mem = new Obect();
   
    // 생성된 객체에 속성 추가
    mem.id = "gildone";
    mem.name = "홍길동";
    mem_addr = "대전" ;
   
    mem.toString = function(){
        var str = "이름 : "+this.name + "\n";;
        str += "ID : "+this.id + "\n";
        str +="주소 : "+ this.addr;
       
        alert(str);
    }
   
    //alert(mem.id);
    mem.toString();
   
//---------------------
  </script>
</head>
<body>

</body>
</html>

JSON 표기법-- 자바스크립트 오브젝트 심플 표기법

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>img 커텐 효과 </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
     //JOSN 표기법
   
    // 1. 이름:값 형식
   
    var mem= {id : "power2c","name" : "일지매",addr: "대전"};
   
    document.write(mem.name+ "씨!!<br>당신은 ID가 "+mem.id+"이고, " +mem.addr+"에 사시는군요 !! <br><br>");

    // 2. 배열 형식
    var names = ["홍길동","일지매","변학도","성춘향","이몽룡"];
   
    for(var i=0;i<names.length;i++){
        document.write("names["+i+"] j = "+ names[i]+"<br>");
       
       
    }
    document.write("<br><hr color='red'><br> ")
 
  </script>
</head>
<body>

</body>
</html>

 

사용자 객체 생성및 사용

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript" src="./js/jquery-1.7.2.js">
        </script>
        <script type="text/javascript">
/*
    학번, 이름, 국어점수 , 수학점수, 컴퓨터 점수, 총점, 평균을 기억할 속성을 갖고
    총점과 평균은 메소드를 이용하여 구하는 클래스를 작성 하시오. 

    속성
        학번,이름,국어,수학,컴퓨터,총점,평균
    메소드
        총점구하기
        평균구하기
        결과출력하기
 */
    var Student= function(myNo,myName,myKor,myMat,myCom) {
        this.no =myNo;
        this.name=myName;
        this.kor=myKor;
        this.mat=myMat;
        this.com=myCom;
        this.tot=this.getTot();
        this.avg=this.getAvg();
       
    };
    Student.prototype = {
        getTot : function(){
                var tot = this.kor+this.mat+this.com;
                 return tot;
                 },
        getAvg : function(){
            if(typeof(this.tot)=="undefined"){
                //값이 없는경우 typeof 처리 시에 undefined 라는 문자열이 반환
            }
           
            var avg = this.tot/3;
                return parseInt(avg);
        },
        getDisplay : function(){
            document.write("No : "+this.no+"<br>");
            document.write("name : "+this.name+"<br>");
            document.write("kor : "+this.kor+"<br>");
            document.write("mat : "+this.mat+"<br>");
            document.write("com : "+this.com+"<br>");
            document.write("tot : "+this.tot+"<br>");
            document.write("avg : "+this.avg+"<br>");
        }

    };
   
    var sut = new Student(15,"김훈",82,90,100);
    sut.getDisplay();
            
              
        </script>
    </head>
    <body>
    </body>
</html>

 

추가 JSON 설명

 

 

Introducing JSON - 원문보기

 

참고사항 : 한국어로 번역했을 때 개발자로서 접근하기 불편한 것들은 그냥 한글 발음으로 표기했음.

ex> object -> 오브젝트, format -> 포맷 등

 

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

JSON(자바스크립트 오브젝트 표기법) 은 가벼운 데이터 변환 포맷이다. (즉, 여러가지 언어에서 사용하는 데이터 표현방식을 한가지로 표준화 해서 사용하겠다 라는 말이다. 그런데 발음이... 제이슨? 제이손?제이썬? 뭐가 맞는것인지... 당췌! 자신있는 분 답글 부탁합니다 ㅋㅋ)

 

It is easy for humans to read and write. It is easy for machines to parse and generate.

사람이 읽고 쓰기 편하다. 기계가 분석하고 생성하기가 편하다. (사람도 편하고 기계도 편하다. 꿩먹고 알먹기? 그럼 꿩은 멸종되는 것인가.. ㅡ.ㅡ; )

 

It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.

JSON 은 1999년 12월에 발표된 ECMA-262(에크마-262) 표준 3번째 에디션의 자바스크립트 프로그래밍 언어의 일부를 기반으로 한다.

 

JSON is a text format that is completely language independent

JOSN 은 완전히 프로그램언어와 상관없는 문자 포맷이다.

 

but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

버뜨! 그러나 C, C++, C#, Java, JavaScript, Perl, Python, 기타등등의 C 언어 패밀리 ( C 문법과 유사한 언어들을 의미하는거 같음. 아님말고 ㅡㅡ+) 프로그래머들이 사용하는 형태와 비스무리하다. (번역이 좀 이상하다 - 그냥 의미만 이해하다.)

 

These properties make JSON an ideal data-interchange language.

이런 특징이 JOSN 을 데이타 변환 언어로 사용하게끔 만든다. (왜냐! 거의 모든언어를 사용할 수 있으니까!!)

 

 

JSON is built on two structures:

JSON 은 2가지 구조다.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • 이름/값  이런형식의 집합 : 많은 언어들이 이놈들을 오브젝드, 레코드, 구조체, 딕셔너리, 해쉬테이블, 키값을 가진 리스트, 연상배열(인덱스가 아닌 키값으로 접근 가능한 배열) 로 인식된다.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
  • 값들이 순서대로 나열된 것들 : 대부분 배열, 벡터, 리스트, 시퀀스로 인식한다.

These are universal data structures.

이놈들은 통합된 데이터 구조이다.

 

Virtually all modern programming languages support them in one form or another.

왠만한 언어들이 위에 나열된 데이터형식들을 사용한다는 말이다.

 

It makes sense that a data format that is interchangable with programming languages also be based on these structures.

즉, 이러한 구조를 기반으로 하는 프로그램 언어들은 서로 데이터를 주고 받을 수 있다~~ 라는 말.

 

In JSON, they take on these forms:

JOSN 은 3가지 형식으로 사용되는데....

 

An object is an unordered set of name/value pairs.

오브젝트는 순서 상관없이 이름/값으로 이루어진이다.

 

An object begins with { (left brace) and ends with } (right brace).

{ 로 시작해서 } 로 끝난다. { ~~~ }

 

Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

'이름' 하고 '값' 은 : (콜론) 으로 구분하고 여러개 구분할때는 , (콤마)로 한다.

요롷게,  { 이름1:값1 , 이름2:값2, ... }

 

 

 

An array is an ordered collection of values.

배열은 순서가 있는 값들의 집합이다.

 

An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

[ 로 시작해서 ] 로 끝나고 마찬가지로 , 로 여러개 구분한다.

요롷게, [ 배열1, 배열2, 배열3, ... ]

 

 

 

 

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.

'값'은 " (썅따옴표) 로 싸고있는 문자열, 숫자, 참/거짓, NULL, 오브젝트, 배열을 쓸 수 있다.

 

These structures can be nested.

당근 중첩될 수 있다.

 

 

 

A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.

문자열은 \ (역슬래쉬) 를 이용해서 특수 문자를 넣을 수도 있고, 아예 빈값도 되고, 유니코드도 된다. 단, " 로 감싸줘야 된다.

 

A character is represented as a single character string. A string is very much like a C or Java string.

한글자도 문자열로 취급한다. (char 가 아닌 string... 이해 안되면 자바기초 공부하세요)

 

 

 

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

숫자는 C 랑 Java 하고 비스무리 한데, 8진수, 16진수는 안된다.

 

Whitespace can be inserted between any pair of tokens.

공백은 " 로 감싼 문자열 빼고 어디들 올 수 있다.( 문자열안에 있는 공백 빼고 나머지는 무시한다는 얘기)

 

Excepting a few encoding details, that completely describes the language.

몇가지 규칙빼고 전부 설명했다.

 

-- 원문보기 가보시면 왠만한 언어들은 다 지원된다는 것을 알 수 있습니다.

-- 예제는 안 적었습니다. 구굴링 해보면 나오니까요 ㅋㅋ

-- 나름대로 이해하기 쉽게 설명한다고 했는데... 쉬운지 모르겠네요 ^^;

    조금이라고 도움이 되셨기를...

 

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

list 추출및 select 구현  (0) 2012.05.08
9일차 XML문서  (0) 2012.05.08
7일차 Effects  (0) 2012.05.08
6일차 Utilities  (0) 2012.05.08
5일차 찾기관련()eq()..  (0) 2012.05.08
Posted by 사라링

7일차 Effects

2012. 5. 8. 18:24

01.html 02.html 03.html 04.html 05.html 06.html

 

 

Effects img 보이기 감추기

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
      $(document).ready(function(){
        $("div").css({border:"1px solid black"}).attr("align","center");
       
        $("input#imgShow1").click(function(e){
           
            $("img").show();
        });
        $("input#imgShow2").click(function(e){
            //$("img").show(3000); // 시간은 밀리세컨드(1/1000초 단위)
            // 숫자 대신 "slow","normal","fast"를 사용 할수 있다.
            //slow => 600 // normal=> 400 , fast=> 200이다.
            $("img:not(animated)").show("slow");
           
        });
        $("input#imgShow3").click(function(e){
            $("img").show(1000,function(){
                alert("보이기 작업이 모두 끝났습니다.")
            });
        });
        $("input#imgHide1").click(function(e){
            $("img").hide();
        });
        $("input#imgHide2").click(function(e){
            //$("img").hide(3000);
            $("img:not(:animated)").hide(300);
        });
        $("input#imgHide3").click(function(e){
            $("img").hide(1000,function(){
                alert("감추기 작업이 모두 끝났습니다.");
            });
        });
        $("input#imgToggle").click(function(e){
            //$("img").toggle();
            //$("img").toggle(1000);
            $("img").toggle(1000);
           
           
           
        });
    });
  </script>
</head>
<body>
    <input type="button" id="imgShow1" value="이미지보이기"/>
    <input type="button" id="imgShow2" value="천천히보이기"/>
    <input type="button" id="imgShow3" value="보이기후 처리"/><br>
   
    <input type="button" id="imgHide1" value="이미지감추기"/>
    <input type="button" id="imgHide2" value="천천히감추기"/>
    <input type="button" id="imgHide3" value="감추기후 처리"/><br>
   
    <input type="button" id="imgToggle" value="보이기<->감추기"/>
   
    <div><img src="./image/a1SA.jpg" style="display:none;" alt="걸"></div>
</body>
</html>

 

Fade 효과  // img 의 불투명도 조정

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>img의 불투명도에 효과를 주어 사라지거나 나타나게 한다. </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
      $(document).ready(function(){
        $("div").css({border:"1px solid black"}).attr("align","center");
       
        $("input#imgFadeIn").click(function(e){
           
            //$("img").fadeIn(2000);
            $("img").fadeIn(2000,function(){
                alert("인 작업 종료")
            });
        });
        $("input#imgFadeOut").click(function(e){
           
            //$("img").fadeOut(2000);
            $("img").fadeOut(2000,function(){
                alert("아웃 작업 종료")
            });
        });
        $("img").mouseover(function(e){
            $(this).fadeTo(1000,0.2);
        });
        $("img").mouseout(function(e){
           
            $(this).fadeTo(1000,1);
        });

    });
  </script>
</head>
<body>
    <input type="button" id="imgFadeIn" value="이미지 FadeIn"/>

    <input type="button" id="imgFadeOut" value="이미지 FadeOut"/>
   
   
    <div><img src="./image/a1SA.jpg" style="display:none;" alt="걸"></div>
</body>
</html>

 

sliding 효과 // 일명 커텐 효과

 

slideDown // 보여주는것 slideUp  사라 지는것

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>img 커텐 효과 </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
      $(document).ready(function(){
        $("div").css({width:200,height:200,border:"1px solid black"})
       
        $("input#imgSlideDown1").click(function(e){
           
            $("div").attr("align","center");
            $("img").slideDown(2000);

        });
        $("input#imgSlideDown2").click(function(e){
           
            $("div").attr("align","right");
            $("img").slideDown(2000);

        });
        $("input#imgSlideDown3").click(function(e){
           
            $("div").attr("align","left");
            $("img").slideDown(2000);

        });
        $("input#imgSlideUp1").click(function(e){
           
            $("div").attr("align","center");
            $("img").slideUp(2000);

        });
        $("input#imgSlideUp2").click(function(e){
           
            $("div").attr("align","right");
            $("img").slideUp(2000);

        });
        $("input#imgSlideUp3").click(function(e){
           
            $("div").attr("align","left");
            $("img").slideUp(2000);

        });
        $("input#imgSlideToggle").click(function(e){
           
            $("div").attr("align","center");
            $("img").slideToggle(2000);

        });
    });
  </script>
</head>
<body>
    <input type="button" id="imgSlideDown1" value="이미지 SlideDown(가운데정렬)"/>
    <input type="button" id="imgSlideDown2" value="이미지 SlideDown(오른쪽정렬)"/>
    <input type="button" id="imgSlideDown3" value="이미지 SlideDown(왼쪽 정렬)"/>
    <input type="button" id="imgSlideUp1" value="이미지 SlideUp(가운데정렬)"/>
    <input type="button" id="imgSlideUp2" value="이미지 SlideUp(오른쪽정렬)"/>
    <input type="button" id="imgSlideUp3" value="이미지 SlideUp(왼쪽 정렬)"/>
    <input type="button" id="imgSlideToggle" value="이미지 SlideToggle(가운데정렬)"/>

   
    <div><img src="./image/203785_1333538468_7QtpDvwsT2FhlVyJ.gif" style="display:none;" alt="걸"></div>
</body>
</html>

 

사용자효과 ease효과  http://jqueryeasing.com/

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>사용자 정의 효과 </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript" src="./js/jquery.easing.1.3.js"></script>
  <script type="text/javascript">
      $(function(){
        $("div").css({width:330,height:330,border:"1px solid black"})
       
        $("#imgAni1").click(function(){
            //$("img").animate({width:"100%",height:"100%",opacity:0.4},2000);
            $("img").animate({width:"+=200",height:"+=200",opacity:0.4},2000);
            // +=현재값 보다 width 가 200만큼 증가 한다.
            // -=현재값 보다 width 가 200만큼 감소 한다.
        });
        $("#imgAni2").click(function(){
            $("img").animate({marginLeft:200},{duration:2000 ,easing:"easeOutBounce"});
            // 이클립스 IE 실행 안됨.
        });
        $("#imgAni3").click(function(){
            $("img").animate({marginLeft:100},1000);
            //$("img").animate({marginTop:100},1000);
            //본래는 오른쪽으로 밑으로 가야하나 밑에 것과 같이 사용 하면
            // 대각선 으로 움직임. queue 를 false 주었을때 나오는 효과
            $("img").animate({marginTop:100},{duration:1000,queue:false});
        });

    });
  </script>
</head>
<body>
    <input type="button" id="imgAni1" value="이미지 Animate1"/>
    <input type="button" id="imgAni2" value="이미지 Animate2"/>
    <input type="button" id="imgAni3" value="이미지 Animate3"/>

   
    <div><img src="./image/203785_1333538468_7QtpDvwsT2FhlVyJ.gif"  alt="걸"></div>
</body>
</html>

 

 추가

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>사용자 정의 효과 </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript" src="./js/jquery.easing.1.3.js"></script>
  <script type="text/javascript">
      $(function(){

        $("#aniTest").click(function(){
            runAni();
//            $("div").show("slow");
//            $("div").animate({left:"+=200"},2000);
//            $("div").queue(function(){
//                $(this).addClass("newcolor");
//                $(this).dequeue();
//            });
//           
//            $("div").animate({left:"-=200"},2000);
//            $("div").queue(function(){
//                $(this).removeClass("newcolor");
//                $(this).dequeue();
//            });
//           
//            $("div").slideUp();
//           
        });
            function runAni(){
           
            $("div").show("slow");
            $("div").animate({left:"+=200"},2000);
            $("div").queue(function(){
                $(this).addClass("newcolor");
                $(this).dequeue();
            });
           
            $("div").animate({left:"-=200"},2000);
            $("div").queue(function(){
                $(this).removeClass("newcolor");
                $(this).dequeue();
            });
           
            $("div").slideUp("normal",runAni);
           
        };
       
       
    });
  </script>
<style type="text/css">
    div{position:absolute; width:40px; height:40px; left:0px; top:50px; display:none;  background-color:#66cccc;}
    div.newcolor{background-color:blue;}
</style>
</head>
<body>
    <input type="button" id="aniTest" value="실행" /><br><br>
   
    <div></div>
</body>
</html>

 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>사용자 정의 효과 </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript" src="./js/jquery.easing.1.3.js"></script>
  <script type="text/javascript">
      $(function(){
        $("#aniTest").click(function(){
            $(".block:first").animate({left:100},
            {duration:1000,
             step: function(now,fx){
                 $("#msg").append(now+"<br>");
                $(".block:gt(0)").css("left",now);
             }    });
        });
    });
  </script>
<style type="text/css">
    div.block{position:relative; width:40px; height:40px; margin:5px; float:left; background-color:#66cccc;}
</style>
</head>
<body>
    <input type="button" id="aniTest" value="실행" /><br><br>
   
    <div class="block"></div><div class="block"></div>
    <div class="block"></div><div class="block"></div>
    <div class="block"></div><div class="block"></div>
   
    <br><br>
   
    <span id="msg"></span>

</body>
</html>

 

 

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

9일차 XML문서  (0) 2012.05.08
8일차 사용자정의객체&JSON표기법  (0) 2012.05.08
6일차 Utilities  (0) 2012.05.08
5일차 찾기관련()eq()..  (0) 2012.05.08
4일차 Methods  (0) 2012.05.08
Posted by 사라링

6일차 Utilities

2012. 5. 8. 18:24

jQuery Utilities

01.html 02.html 03.html

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery Utilities</title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
      $(function(){
        var result ="";
        var testArr = [100,200,300,400];
        var testObj = {"name":"홍길동","addr":"대전","tel":"042-222-8202"};
        var str="";
        $.each(testArr,function(i,v){
            str +=i+" : "+v+"\n";
        });
        alert(str);
        str="";
        $.each(testObj,function(i,v){
            str +=i+" : "+v+"\n";
        });
        alert(str);
       
        jQuery.each(jQuery.browser,function(i,val){
            result +=i+" : "+val +"\n";
        });
        alert(result);
        if($.browser.msie){
            alert("IE브라우저");
        }else {
            alert("다른 웹 브라우저");
        }
       
       
       
        var s = " Abc Def Fed Cba ";
        alert("["+s+"]");
        alert(s.length);
        alert("["+$.trim(s)+"]");
        alert(jQuery.trim(s).length);
       
        var empty={}
        var defaults = {validate:false,limit:5, name : "foo"};
        var options1 =["one","two","three","four","five"];
        var options2 =["six","seven","eight","nine","ten"];
        var settings=$.extend(empty,defaults,options1,options2);
        var result2="";
        jQuery.each(settings,function(i,val){
                result2 +="[name: "+i+"]"+"[value : "+val+"]\n";
        });
        alert(result2);
        $(document).ready(function(){
            var arr1 = [0,1,2,3,4,5,6,7,8,9];
            var arr2 = jQuery.grep(arr1,function(val,i){
                            // 주의점 ./ grep 과 each 인 경우 i 와 value 순서가 다르다. value 가 먼저.
                    return(val!=5&&val>3);
                    // 4 6 7 8 9 가 arr2 에 들어 간다
            });
            alert("변경전: "+arr1.join(",")+"\n"+"변경후: "+arr2.join(","));
            var arr3 =jQuery.grep(arr1,function(n,i){
                return(n!=5&&i>3);
                ///0,1,2,3,5 가 arr3에 입력
               
            },true);// 마지막에 true 가 설정 되면 false를 반환 하는 자료만 취합 한다.
            alert("변경전: "+arr1.join(",")+"\n"+"변경후: "+arr3.join(","));
           
            var arr = jQuery.makeArray($("div"));
            // div 를 배열로 만들어 arr로 넣는다.
            var result3="";
            jQuery.each(arr,function(i){
                result3 += "index["+i+"] element["+$(this).text()+"]\n";
            });
            alert(result3);
           
            result3="";
            var arr =["성춘향",40,"일지매",55,"홍길동",40];
            result3="홍길동 위치"+jQuery.inArray("홍길동",arr)+"\n";
            // inArray <== 대상 배열에서 "홍길동"의 index 값을 반환 한다 .
            result3 +="40위치 : " +jQuery.inArray(40,arr)
            alert(result3);
        });
    });
  </script>
</head>
<body>
<body>
    <div>계룡산</div>
    <div>백두산</div>
    <div>한라산</div>
    <div>지리산</div>
    <p>태백산</p>
    <p><div>소백산</div></p>   
</body>
   
   

</body>
</html>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    var testNull =null;
    var testVal="값이 있는 변수";
    function testFunc(){
        alert("함수입니다.");
    }
    $(document).ready(function(){
        var result="";
        var arr=jQuery.unique(jQuery.makeArray($("div")).concat($("div").get()));
        jQuery.each(jQuery.unique(arr.concat(arr)),function(i){
            result +="[index:"+i+"][value:" +$(this).text()+"]\n";
        });
        alert(result);
        var objs=[testNull,testVal,testFunc];
        result="";
        jQuery.each(objs,function(i){
            result +="[value:"+objs[i]+"]"+"["+$.isFunction(objs[i])+"]\n";
        });
        result="";
    });
   
   
</script>
</head>
<body>
    <div>하나</div>
    <div>둘</div>
    <div>셋</div>
    <div>넷</div>
</body>
</html>

 

 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var arr1 = ["a","b","c","d","e"];
        var arr2 = jQuery.map(arr1,function(n,i){
            return(n.toUpperCase());
        });
        alert("변경전 : "+arr1.join(",")+"\n"+   "변경후: "+arr2.join(","));
    });
</script>
</head>
<body>

</body>
</html>

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

8일차 사용자정의객체&JSON표기법  (0) 2012.05.08
7일차 Effects  (0) 2012.05.08
5일차 찾기관련()eq()..  (0) 2012.05.08
4일차 Methods  (0) 2012.05.08
3일차 export/change  (0) 2012.05.08
Posted by 사라링

5일차 찾기관련()eq()..

2012. 5. 8. 18:24

Traversing - 찾기 관련 메서드

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function(){
//        $("div:eq(1)")
//            .siblings().css("border","1px solid blue")
//            // div2번째의 형재들(자기 자신을뺀) 에게 적용
//            .end()
//            .next().text("third")
//            //div2번째의 다음번째div에 적용
//            .end()
//            .nextAll().css("background","yellow");
//            //2번째 이후에 나오는 모든 div에 적용
//           
//        $("div").find("p").css("color","blue")
//            .add("span").css("border","1px solid red");
//           
        // children() ==> 바로 아래의 자식 엘리먼트만 검색 한다.
        // contents() ==> 바로 아래의 모든 자식 요소들(문자데이터도 포함)을 검색한다.
//        var str="";
//        $("div:eq(0)").children().each(function(i,v){
//            str +=i + " : tagName = "+v.tagName + " ==> "+$(v).html()+"\n";
//        });
//        str="";

//        $("div:eq(0)").contents().each(function(i,v){
//            if(typeof(v.tagName)==undefined){
//                str += i+" : "+$(v).text()+"\n";
//            }else {
//            str +=i + " : tagName = "+v.tagName + " ==> "+$(v).html()+"\n";
//            }
//        });
//        alert(str);
//        $("p:eq(0)").parent().css("border","2px solid red");
       
//        var str="";
//        $("p:eq(0)").parent().each(function(){
//            str+=this.tagName+"\n";
//        });
//        alert(str);
//        $("div:eq(3)").prevAll().css("backgroundColor","yellow");
        $("div:eq(3)").prev().css("backgroundColor","yellow");
       
    });   
   
</script>
<style type="text/css">

    div{width:100px; height:100px; margin:10px; float:left;
    border:1px solid silver; padding:5px;}
   
</style>
</head>
<body>
    <div>A<p>p a</p><span>span a<span>span a a</span></span></div>
    <div>B<p>p b</p></div>
    <div>C<p>p c</p></div>
    <div>D<br><span>span d</span></div>
    <div>E<br><span>span e</span></div>
</body>
</html>

 

CSS 관련 메서드

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>속성 설정 하기(추가 삽입)</title>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function(){
        alert($("img").eq(0).attr("src"));
        $("#photos img")
        .attr({"border":"1px","height":"100"})
        .attr("title",function(i){
            return(i+1)+"번째 이미지 입니다.";
        });
       
        //alert($("body").html());
        $("#photos img").eq(-1).removeAttr("title");
            // 마지막 번째 의 title 속성을 제거
    });
   
   
</script>
</head>
<body>
    <div id="photos">
        <img src="image/한글.jpg"/>
        <img src="image/2.jpg"/>
        <img src="image/3GFST.jpg"/>
        <img src="image/8f62be078e54cf04d3b918de815939d3.jpg"/>
        <img src="image/a1SA.jpg"/>
       
       
       
       
    </div>
   
   

</body>
</html>

이벤트(Event) 관련 메서드

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>이벤트 관련 메서드</title>
</head>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function(){
        $("#myBtn").bind("click",{name:"홍길동",gender:"남자"},
        //이벤트를 처리하는 함수의 파라미터 변수는 이벤트 객체 변수이다.
        function(e){
            alert("제 이름은 "+e.data.name+"이고,"+e.data.gender+"입니다.");
        });
        $("#myMT").one("click",function(){
            alert("이미지는 클릭 하지 마세요. 두번 말하지 않습니다.");
        });
        $("#testTrgg").bind("myTriggerOne",function(){
            $(this).attr("src","./image/2.jpg");
        });
        $("#testTrgg").bind("myTriggerTwo",function(){
            $(this).attr("src","./image/3GFST.jpg");
        });
        $("#trggBtn").toggle(
            function(){$("#testTrgg").trigger("myTriggerOne")},
            function(){$("#testTrgg").trigger("myTriggerTwo")}
        );
        $("#testHover").hover(
            function(){$(this).css("border","2px solid blue")},
            function(){$(this).css("border","0px")}
       
        );
    });
   
</script>
<body>
<div>
    <span id="testHover"><img id="myMT" src="./image/a1SA.jpg"></span>
    <img id="testTrgg" src="./image/8f62be078e54cf04d3b918de815939d3.jpg"/>
</div>
<input type="button" id="myBtn" value="내 소개!!">
<input type="button" id="trggBtn" value="Trigger Test">



</body>
</html>

 

 

 

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

7일차 Effects  (0) 2012.05.08
6일차 Utilities  (0) 2012.05.08
4일차 Methods  (0) 2012.05.08
3일차 export/change  (0) 2012.05.08
2일차 Selectors  (0) 2012.05.08
Posted by 사라링

4일차 Methods

2012. 5. 8. 18:24

jQuery Methods

 

추가 메서드

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New Document</title>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>

    <script type="text/javascript">
        $(function(){
/*
            alert ("변경전\n\n" + $("#test1").html() );

            $("#test1").html($("#test1").html() + "<span>새롭게 추가되는 내용입니다.</span>");

            alert ("변경후\n\n" + $("#test1").html() );
*/           
/*           
            alert ("변경전\n\n" + $("#test1").text() );

            $("#test1").text($("#test1").html() + "<span>새롭게 추가되는 내용입니다.</span>");
*/
        $("#btn").click( function(){

            //alert( $("#name").val() );   

            $("#name").val( "낄낄낄" );

        });
       
        //$("#test1").append("<font color='red'>새로운 내용(append)</font>");
        //$("<font color='red'>새로운 내용(appendTo)</font>").appendTo("#test2");

        //$("#test1").prepend("<font color='red'>새로운 내용(prepend)</font>");
        //$("<font color='red'>새로운 내용(prependTo)</font>").prependTo("#test2");
       
        // 기존의 문서 내용을 append 또는 prepend 하면 그 내용이 이동한다.
        //$("#test1").append( $("#test3") );
        //$("#test3").appendTo("#test2");

        //$("#test1").prepend( $("#test3") );
        //$("#test3").prependTo("#test2");

        //alert( $("body").html() );

        //$("#test1").after("<font color='red'>새로운 내용(after)</font>");
        //$("<font color='red'>새로운 내용(insertAfter)</font>").insertAfter("#test2");

        //$("#test1").before("<font color='red'>새로운 내용(before)</font>");
        //$("<font color='red'>새로운 내용(insertBefore)</font>").insertBefore("#test2");   
       
        //$("#test1").after( $("#test3") );
        //$("#test1").before( $("#test3") );

        //$("h2").wrap("<font color='green'></font>");
        //$("h2").wrap("<font color='green'>font태그</font>");
       
        //$("h2").wrapAll("<font color='green'></font>");
        $("h2").wrapAll("<font color='green'>font태그</font>");

        alert( $("body").html() );

    });

    </script>
    <style type="text/css">
        div { border: 1px solid red; margin:5px;}
    </style>
 </head>

 <body>
    <input type="text" id="name"><input type="button" id="btn" value="확인">
    <br><br>

    <h2>jQuery 메소드 예제</h2>

    <div id="test1">
        <span>첫째...</span><br>
        둘째...
        <p>셋째...</p>
    </div>

    <div id="test2">
        <span>첫째...</span><br>
        둘째...
        <p>셋째...</p>
    </div>
   
    <span id="test3">
        <h2>안녕하세요1</h2>
        <h2>안녕하세요2</h2>
        <h2>안녕하세요3</h2>
        <h2>안녕하세요4</h2>
    </span>
 </body>
</html>

삭제 메소드

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New Document</title>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function() {
        $(".annotation").each(function(i){
            var no =i+1;
            $(this).after("<sub>"+no+"</sub>");
        });
        var rmBtn =null;
        $("button").click(function(){
            alert($(this).val());
//            rmBtn=$(this).remove();
            rmBtn=$(this).detach();
            $("#detachTest").append(rmBtn);
        });
        var $prev=$("#prevBtn").clone();
        // 걍 클론 은 기능은 복사 안함
        var $next=$("#nextBtn").clone(true);
        // 클론에 true까지 포함 => 기능까지 복사
       
        $("div#bottomDiv").prepend($prev);
        $("div#bottomDiv").append($next);

    });
</script>
</head>


<body>
    <button id="prevBtn">이전 페이지로</button>
    <button id="nextBtn">다음 페이지로</button>
    <h3>jQuery</h3>
    <div><b>jQuery</b>는 가볍고 빠르며,간결한<span class="annotation">오픈소스</span>
    스크립트라이브러리 입니다. <br>이를 이용하면 Rich 웹 UI를 개발 하는데 도움이 되는 다양한
    기능들<br>즉,HTML 문서 <span class="annotation">트래버스</span>,
    이벤트처리,애니메이션,<span class="annotation">Ajax</span>상호작용등을 지원하여
    <br>빠르고 견고하게 리치 웹 애플리케이션 개발을 할수 있도록 지원 합니다.
    </div><br>
    <div id="bottomDiv"><span>기준</span></div>
    <div id="detachTest">detach연습</div>
</body>
</html>
.

횡단*(Traversing) 메서드

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function(){
        $("div").eq(0).addClass("lightblue");
        $("div").filter(":odd")
            .eq(0).css("background","orange")
            .end()    // 방금 실행한 집합 이전으로 되돌린다.
            .eq(1).css("background","blue")
            .end()
            .css("color","red");
        var $myDiv=$("div").eq(5);
        if($myDiv.is("div"))$myDiv.css("border","4px solid yellow");
        if($myDiv.is(".orange, .blue, .lightblue"))$myDiv.text("칼라");
   
        $("div").each(function(){
            $(this).text($(this).text().toUpperCase());
        });
       
    });

</script>
<style>
    div{width:60px; height:60px; margin:10px; float:left; border:2px solid blue;}
    .blue {background:blue;}
    .lightblue {background:lightblue;}
    .orange {background:orange;}
</style>

</head>
<body>
    <div>a</div>
    <div>b</div>
    <div>c</div>
    <div>d</div>
    <div>e</div>
    <div class="orange">f</div>
    <div>g</div>
</body>
</html>

 

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

6일차 Utilities  (0) 2012.05.08
5일차 찾기관련()eq()..  (0) 2012.05.08
3일차 export/change  (0) 2012.05.08
2일차 Selectors  (0) 2012.05.08
1일차 get/function  (0) 2012.05.08
Posted by 사라링

3일차 export/change

2012. 5. 8. 18:24

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
 $(function(){
  $("span:contains('JQuery')").css("border","1px sllid blue");//JQuery 를 포함 하는span 테그를 변경 . 
  $("span:not(:contains('JQuery'))").css("border","1px solid red");
 });// JQuery를 포함 하지 않는 span 테그를 변경 컨텐츠 를 변경
  </script>

  <style type="text/css">
 *{font-size:12px;font-family:돋음}
  </style>
 </head>

 <body>
  <div>Hello,<span>Enjoy developing!</span></div>
  <p>It's another sector!<span>Thanks, JQuery!</span></p>
  <div class="myClsaa">JQuery!</div>
  <span class="notMyclass">It's so easy!</span>
 </body>
</html>

 

//

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
 $(function(){
  $("td:empty").text("새로운값").css("background","yellow");
 });     // td 중 비어있는 것을 찾아 새로운값및 백그라운드 색상을 변경.
/*  $(selector).text(); // selector 의 내용중 문자열만 추출한다.
 $(selector).html(); // selector 의 내용중 html코드로 추출한다.
 $(selector).text("내용"); // selector자리에 '내용'을 문자열 형태로 넣어 준다.
                             //내용에 html코드가 포함되어도 이 html 코드를 해석하지 않고 문자열 형태로 그대로 나타낸다.
 $(selector).html("내용"); // selector 자리에 '내용'을 html 형식으로 넣어 준다.
  */
  </script>
  <style type="text/css">
 *{font-size:12px; font-family:돋음}
  </style>
 </head>

 <body>
  <table border="1">
  <tr><td>TD 1-1</td><td></td></tr>
  <tr><td>TD 2-1</td><td></td></tr>
  <tr><td></td><td>TD 3-2</td></tr>
 </body>
</html>

 

 

 

 

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
 $(function(){
  $("div:has(span)").css("border","1px solid blue");
 });
     // span 테그를 포함 하는 div 테그를 찾아서 변경 하라.
  </script>
  <style type="text/css">
 *{font-size:12px; font-family:돋음}
  </style>
 </head>

 <body>
  <div>
 Hello,<span>Enjoy developing!</span><div class="myClass">JQuery!</div>
  </div>
  <p>It's another sector!<span>Thanks,JQuery!</span></p>
  <span class="notMyClass">It's so easy!</span>
 </body>
</html>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
    $("td:nth-child(3)").css("backgroundColor","yellow");
    //각 td 그룹을 따로 나눈후 3번째 것을 찾아 변경
    $("td:nth-child(odd)").css("backgroundColor","cyan");
    // 그룹 나눈것중 홀수 번째
    $("td:nth-child(even))").css("backgroundColor","red");
    //그룹 나눈것중 짝수 번째
    $("td:nth-child(3n+1)").css("backgroundColor","pink");
    // '3n+1'와 같은 식의 n자리에 0,1,2,3,.. 을 차례로 대입 하여 계산한 결과의 위치를 선택 한다.
    $("td:first-child").css("backgroundColor","yellow");
    //각 그룹별로 첫번째 것을 찾아 적용 한다.
    $("td:last-child").css("backgroundColor","cyon");
    //각 그룹별로 마지막 것을 찾아 적용 한다.
    $("td:only-child").css("backgroundColor","green");
    // 자신이 부모 테그의 유일한 자식일때 적용 .그룹 적용된것에 하나 뿐일때 를 말하는것임
   
});
</script>

</head>
<body>
<table border="1">
<tr><td>TD #1 </td> <td>TD#2</td><td>TD#3</td><td>TD #4</td></tr>
<tr><td>TD #5 </td> <td>TD#6</td><td>TD#7</td><td>TD #8</td></tr>
<tr><td>TD #9 </td> <td>TD#10</td><td>TD#11</td><td>TD #12</td></tr>
</table>
<hr>
<table border="1">
<tr><td>TD #1 </td> <td>TD#2</td><td>TD#3</td><td>TD #4</td>
<td>TD #5 </td> <td>TD#6</td><td>TD#7</td><td>TD #8</td>
<td>TD #9 </td> <td>TD#10</td><td>TD#11</td><td>TD #12</td></tr>
</table>
<hr>
<table border="1">
<tr><td>TD#1</td><td>TD#2</td><td>TD#3</td></tr>
<tr><td colspan="3">TD#4</td></tr>
<tr><td colspan="2">TD#5</td><td>TD #6</td></tr>
</table>
</body>
</html>

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New Document</title>
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function() {
        function testChecked() {
            var result = "";
            $(":checkbox:checked").each(function() {
                if (result != "")
                    result += ",";
                result += $(this).val();
                $(this).css("border", "3px solid #6600ff ");
            });
            $(":checkbox:not(:checked)").each(function() {
                $(this).css("border", "0px")
            });
            alert(result == "" ? "취미가 없군요!!" : "취미는 " + result + "이군요!!");
        }// testChecked 끝
        testChecked();
        $(":checkbox").click(testChecked);
        // checkbox를 클릭 하면 'testchecked' 함수를 호출 한다.

        function testSelected() {
            var result = "봄소식 전령사들\n\n";
            $("select[name='spring'] option:selected").each(function() {
                result += $(this).val() + "\n";
                //$(this).css("border", "5px #009999 solid") + "\n";
            });
            alert(result);
        }
        testSelected();
        //$("select[name='spring']").change(testSelected);
        //'select'객체에서 'change'이벤트가 발생 하면 'testSelected'함수를 호출 한다.
        $('#viewSelect').click(testSelected);
        //
    });
</script>
</head>

<body>
    <form>
        취미 : <input type="checkbox" name="hobby" value="여행" checked>여행
        <input type="checkbox" name="hobby" value="장기" />장기 <input
            type="checkbox" name="hobby" value="바둑" />바둑 <input type="checkbox"
            name="hobby" value="독서" checked>독서 <input type="checkbox"
            name="hobby" value="낚시" />낚시<br> 봄소식 : <select name="spring"
            multiple="multiple" size="6">
            <option>개나리</option>
            <option selected>진달래</option>
            <option>민들레</option>
            <option selected>벚꽃</option>
            <option>목련</option>
            <option>철쭉</option>
        </select><br>
        <input type="button" id="viewSelect" value="봄소식보기"/>
    </form>
</body>
</html>

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

5일차 찾기관련()eq()..  (0) 2012.05.08
4일차 Methods  (0) 2012.05.08
2일차 Selectors  (0) 2012.05.08
1일차 get/function  (0) 2012.05.08
16일차 우편번호검색(json)  (0) 2012.05.08
Posted by 사라링

2일차 Selectors

2012. 5. 8. 18:24

Jquey Selectors


$(function(){
//    $("#list").css("border","1px solid silver");
//    $("p").css("border","2px solid red");
//    $("span").css("background-color","pink").css("color","#009999");
//    $("span a").css("text-decoration","overline").css("color","#000000");
//    $("span.detail").css("color","blue");
//    $("div~b").css("background","green");
    $("div>b").css("border","1px solid red");
//    $("div+b").css("border","2px solid blue");

});


    $(document).ready(function() {
        $("img[alt]").css("border", "1px solid red");
        // img 속성에 alt가 있는것 .
        $("input[type='button']").css("background-color", "yellow");
        // 인풋 타입이 버튼인것
        $("a[href^='mailto:']").css("background-color", "lightblue");
        // a테그 중에 href가 mailto: 로 시작 하는것
        $("img[id!='hibiscus']", $("div")).css("border", "3px solid blue");
        //img id 속성이 hibiscus가 아닌것 $("div"), 안에서 img 테그를 찾아서 적용 하라 
        $("img[src$='jpg']").css("border", "2px solid #00ffff");
        //img 의 src 속성이 .jpg로 끝나는 것($=) 
        $("a[href*='power2c']").css("text-decoration", "none");
        //a 의 href 속성이 포함(*=) 되어 있는것 power2c 가 ..
        $("img[id|='little']").css("border", "2px solid green");
        //img id 값이 little 이거나 little-xxx 인것. 반드시 '-' 가 있어야 한다.
        $("img[title~='named']").css("border", "2px solid pink");
        // img의 title 에 named 라는 단어가 있는것 포함이 아니라 하나의 단어로 구성 되어야 한다.
        //A puppy named Cozmo <== 는 적용 되나 A puppynamed Cozmo 는 적용 되지 않는다.
    });


 

 

 

 

 

 1. CSS셀렉터

<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
//    $("#list").css("border","1px solid silver");
//    $("p").css("border","2px solid red");
//    $("span").css("background-color","pink").css("color","#009999");
//    $("span a").css("text-decoration","overline").css("color","#000000");
//    $("span.detail").css("color","blue");
//    $("div~b").css("background","green");
    $("div>b").css("border","1px solid red");
//    $("div+b").css("border","2px solid blue");

});
 
</script>
</head>
<body>
<div>
    <span>IT교육의 요람<a href="http://ddit.or.kr">(재)대덕인재 개발원</a>으로 오세요</span><br><br>
    <a href="mailto:power2c@ddit.or.kr">빠워에게 메일 보내기 </a>
    <p>
    RIA기술 : <input type="checkbox" name="ria" value="플렉스">플렉스
    <input type="checkbox" name="ria" value="실버라이트">실버라이트
    <input type="checkbox" name="ria" value="HTML5">HTML5
    성별<input type="radio" name="sex" value="여자">"여자"
    <input type="radio" name="sex" value="남자">"남자"
    <input type="button" value="클릭~~"><br>
    </p>
    <div id="list">selector의 종류 들입니다.</div>
   
    <b>엘리멘트 : </b><span class="detail"><b>태그명,ID 속성값,CLASS속성값이용</b></span><br>
    <b>속성 : </b><span class ="detail">각 요소에 설정된 속성명과 속성값 이용</span><br>
    <b>form : </b><span class = "detail">input,select,textarea등의 특성을 이용</span>
</div>

 

2.속성 관련 CSS셀렉터들

<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("img[alt]").css("border", "1px solid red");
        // img 속성에 alt가 있는것 .
        $("input[type='button']").css("background-color", "yellow");
        // 인풋 타입이 버튼인것
        $("a[href^='mailto:']").css("background-color", "lightblue");
        // a테그 중에 href가 mailto: 로 시작 하는것
        $("img[id!='hibiscus']", $("div")).css("border", "3px solid blue");
        //img id 속성이 hibiscus가 아닌것 $("div"), 안에서 img 테그를 찾아서 적용 하라 
        $("img[src$='jpg']").css("border", "2px solid #00ffff");
        //img 의 src 속성이 .jpg로 끝나는 것($=) 
        $("a[href*='power2c']").css("text-decoration", "none");
        //a 의 href 속성이 포함(*=) 되어 있는것 power2c 가 ..
        $("img[id|='little']").css("border", "2px solid green");
        //img id 값이 little 이거나 little-xxx 인것. 반드시 '-' 가 있어야 한다.
        $("img[title~='named']").css("border", "2px solid pink");
        // img의 title 에 named 라는 단어가 있는것 포함이 아니라 하나의 단어로 구성 되어야 한다.
        //A puppy named Cozmo <== 는 적용 되나 A puppynamed Cozmo 는 적용 되지 않는다.
    });
</script>
<style type="text/css">
    *{font-size: 12px; font-family: 돋움}
</style>

</head>
<body>
<div>
        <a href="http://ddit.or.kr">(재)대덕인재 개발원</a><br><br>
    <a href="mailto:power2c@ddit.or.kr">빠워에게 메일 보내기 </a><br><br>
    <div>
        <img alt="Hibiscus" src="images/image.1.jpg" id="hibiscus"/>
        <img title="A dog nameed Little Bear" src="images/image.2.jpg" id="little-Bear"/>
        <img alt="Verbena" src="images/image.3.jpg" id="verbena"/>
        <img title="A puppy named Cozmo" src="images/image.4.jpg" id="cozmo"/>
        <img alt="Tiger Lily" src="images/image.5.jpg" id="tigerLily"/>
        <img title="coffeePot" src="images/image.6.jpg" id="little"/>
    </div>
    <div id = "someDiv">이곳은 ID속성이 <tt>someDiv</tt>인 &lt;div&gt;테그 입니다</div>
    <div title="myTitle"><span>Hello</span></div>
    <div title="myTitle"><span>Goodbye</span></div>
    <form onsubmit="return false;">
        <div>
            <label>Text:</label><input type="text" id="aTextFiled" name="someTextField"/>
        </div>
        <div>
            <label>Radio group:</label>
            <input type="radio" name="radioGroup" id="radioA" value="A">A
            <input type="radio" name="radioGroup" id="radioB" value="B">B
        </div>
        <div>
            <label>Checkboxes:</label>
            <input type="checkbox" name="checkboxes" id="checkbox1" value="1">1
            <input type="checkbox" name="checkboxes" id="checkbox2" value="2">2
        </div>
    <button type="submit" id="submitButton">Submit</button>
    <input type="button" value="클릭~~">
    </form>
</div>

3.Form 관련 셀렉터들

<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $(":input").css("border", "2px solid red");
        // 모든 form 테그 적용 안에 적용
        $(":input:button").css("background-color", "yellow");
        // input 테그중 type 이 button 에 적용
        $(":button").css("background-color", "yellow");
        //input 테그중 type이 button 과 button 테그 에 모두 적용
        $(":submit").css("background-color", "pink");
        // 이하 같음 form 안에 type이 submit 인것에 모두 적용
        $(":reset").css("background-color", "yellow");
        $(":checkbox").css("border", "2px solid red");
        $(":radio").css("border", "2px solid red");
        $(":text").css("border", "2px solid red");
        $(":password").css("border", "2px solid red");
        $(":file").css("border", "2px solid red");
        $(":image").css("border", "2px solid red");
    });
</script>
<style type="text/css">
* {
    font-size: 12px;
    font-family: 돋움
}
</style>
</head>
<body>
    <form onsubmit="return false;">
        Text : <input type="text" /> <br /> Password : <input type="password" />
        <br />
        <br /> Radio : <input type="radio" name="radioGroup" id="radioA"
            value="A" />A <input type="radio" name="radioGroup" id="radioB"
            value="B" />B <br />
        <br /> CheckBox : <input type="checkbox" name="checkboxes"
            id="checkbox1" value="1">1 <input type="checkbox"
            name="checkboxes" id="checkbox2" value="2">2<br />
        <br /> Textarea : <br>
        <textarea rows="15" cols="50" id="myTextarea" id="myTextarea"></textarea>
        <br />
        <br /> Images : <input type="image" src="images/image.1.jpg"><br />
        <br /> File : <input type="file"><br />
        <br /> Buttons :
        <button type="submit" id="submitButton">Submit</button>
        <input type="button" value="일반버튼"> <input type="submit"
            value="전송버튼"> <input type="reset" value="초기화버튼">
    </form>
</body>

4.기본 필터

<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function() {
        $("tr").css("text-align", "center");
        // 모든 tr 테그 안에 text를 정렬 하라. 가운데로.
        $(":header:eq(1)").css("font-weight", "bold").css("color", "blue");
        //header 테그 중(h1~h2~h3~ 등)에 2번째 것의 두깨를 bold 색깔을 블루로 변경 하라.
        $("tr:first").css("background", "silver");
        //tr 테그 중에 맨 처음 것의 배경색을 실버로
        $("tr:last").css("background", "yellow");
        //tr 테그 중에 맨 마지막 것의 배경색을 실버로
        $("tr:odd").css("background", "#efefef");
        // tr 테그중 홀수 번째 1.3.5 번째 (0부터 시작 0은 짝수)
        $("tr:even").css("background", "#3388cc");
        // tr 테그중 짝수  번째 0.2.4 번째 (0부터 시작 0은 짝수)
        $("tr:gt(4)").css("background", "silver");
        // tr 테그중 4번째 이전것 을 모두 적용
        $("tr:lt(4)").css("background", "silver");
        // tr 테그중 4번째 이후것 을 모두 적용
    });
</script>
<style type="text/css">
* {
    font-size: 12px;
    font-family: 돋움
}
.scoreTable {
    background: white;
    border-collapse: collapse
}
</style>

</head>
<body>
    <h1>수학 시험 점수1</h1>
    <h2>수학 시험 점수2</h2>
    <h3>수학 시험 점수3</h3>
    <table class="scoreTable" border="1" cellpadding="10">
        <tr>
            <td width="100">이름</td>
            <td width="100">점수</td>
        </tr>
        <tr>
            <td>홍길동</td>
            <td>80</td>
        </tr>
        <tr>
            <td>일지매</td>
            <td>98</td>
        </tr>
        <tr>
            <td>성춘향</td>
            <td>85</td>
        </tr>
        <tr>
            <td>이몽룡</td>
            <td>96</td>
        </tr>
        <tr>
            <td>강감찬</td>
            <td>88</td>
        </tr>
        <tr>
            <td>이순신</td>
            <td>90</td>
        </tr>
        <tr>
            <td>박문수</td>
            <td>92</td>
        </tr>
    </table>
</body>

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

4일차 Methods  (0) 2012.05.08
3일차 export/change  (0) 2012.05.08
1일차 get/function  (0) 2012.05.08
16일차 우편번호검색(json)  (0) 2012.05.08
16일차 select(DBMS:JSON:)  (0) 2012.05.08
Posted by 사라링

1일차 get/function

2012. 5. 8. 18:24

JS 파일을 다운 받자.

http://jquery.com/  오른쪽 가운데에 에서 파일 두개를 받아 저장 하자.

<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>   맨처음 받은 js 파일을 html 폴더에 js 폴더를 생성후에 옮긴후 src 로 연결 해주자.

 

명령어 모음


$(document).ready(function(){
    alert("이것은 $ 이용한 ready 이벤트 입니다. ");
});

$(function(){
    alert("ready이벤트의 축약형 입니다. ");
}); 

// 위 두개는 같은 것이다. 1번째 것을 축약 한것이 2번째 이다.

alert( $("body").html() );

 

$(function(){
    //alert($("p").get(1).innerHTML );
    //alert($($("p").get(1)).html() );
    //alert($($("p").get(1)).text() );
    alert($($("p")[1]).text() );

jQuery.noConflict();// 이 명령 이후에는 jQuery 대신 $ 를 사용 할수 없다.

  var $j = jQuery.noConflict();
    // jQuery 의 애칭인 $ 을 $j 로 변경 한것./ 제이쿼리의 애칭 사용을 금지 하고 제이쿼리객체를 돌려 준다.

    $j(function() {
        alert($j($j("p")[1]).text());
    });

 


 

기본 바디의 onload 명령어를 js 를 이용 하여 이용 한다. window.onload=function(){} or ready 이벤트

기본 명령은 jQuery 이며 애칭은 $ 이다./ 앞으로는 $ 을 되도록 사용 하게 될것이다.

<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>   
<script type="text/javascript">
    function start() {
        alert("안녕하세요 load 이벤트 입니다.");
    }

    //window.onload=start;
    window.onload = function() {
        alert("이것도load 이벤트 입니다. ")
    }

    //ready 이벤트 ==> 문서를 읽어 DOM 구조로 만든후 발생하는 이벤트
    //jQuery 에서는 load 이벤트 대신 ready 이벤트를 이용 한다.
    jQuery(document).ready(function() {
        alert("이것은 ready 이벤트 입니다.");
    });
// jQuery 명령을 대신해서 $ 를 사용 할수 있다.
$(document).ready(function(){
    alert("이것은 $ 이용한 ready 이벤트 입니다. ");
});

$(function(){
    alert("ready이벤트의 축약형 입니다. ");
});
</script>

=======================================================================

 

설명:appendTo("body") 바디의 끝단에 $(<div></div>)의 객체에 test라는 클래스를 지정.

"text" 명령 : "Click Me!!" 텍스트 삽입 . "Click": 명령=>function 명령으로 alert이벤트 발생함.

=========================================================================

<script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
    //$("div").css("background-color","yellow");
    // div 테그를 찾아서 css를 적용 한다.
    $("<div></div>",{
        "class": "test",
        "text" : "Click Me!!",
        "click" : function(){
            alert("클릭 이벤트 입니다.");
        }
    }).appendTo("body");
    //alert( $("body").html() ); // 해당 요소안의 내용을 HTML 코드 형식으로 보여 준다.    
    // 위 아래 는 바디 끝단에 추가 하여 원하는 요소들이 잘 추가가 되어있는지 확인 하는데 유용 하다.
    alert($("body").text() );    // 해당 요소 안의 내용중 문자 데이터만 보여 준다.
});
    //<시작테그명> 내용 </종료테그명>
</script>
</head>
<body>
<div>이 내용은 미리 존재 하는 내용 입니다.11 </div>
<div>이 내용은 미리 존재 하는 내용 입니다.22 </div>
<div>이 내용은 미리 존재 하는 내용 입니다.33 </div>
</body>

설명: .html() 을 이용 하기 위해서 전체 객체로 추출 해야 한다

$("div")[1]<-- div를 객체로 생성 [1] 것의 element추출 한 값을 다시 $() 객채 로 지정 . html()을 실행.

$(function(){
    alert($($("div")[1]).html())
});

설명:size() 와 length 를 이용 하여 내용물의 크기를 알아 추출 가능 하다

<script type="text/javascript">
$(function(){
    //alert("size()==>"+$("p").size());
    //alert("length==>"+$("p").length);
    var str= "";
    $("p").each(function(idx,element){
        str +="indx : "+idx+", data : "+ $(element).text()+"\n";  // $(this).text()+"\n";
    });
    alert(str);
});
</script>

 

<script type="text/javascript">
$(function(){
    var str = "";
   
    var pElement  =$("p").get();
    for(var i=0;i<pElement.length;i++){
        str += $(pElement[i]).html()+"\n";
    }
    alert(str);
});
</script>
</head>
<body>
    <p>첫번째</p>

    <div>
   
        <p>두번째</p>
   
    </div>

    <p>세번째</p>
</body>

설명: get()>>element(내용)추출/ /get(n)=[n] >>n(첨자)번째 내용물 추출

 

 

<script type="text/javascript">
$(function(){
    //alert($("p").get(1).innerHTML );
    //alert($($("p").get(1)).html() );
    //alert($($("p").get(1)).text() );
    alert($($("p")[1]).text() );
   
    //alert($("p").get(1).innerText ); // 폭스 에서는 안대..
   
});
</script>
</head>
<body>
    <p>첫번째</p>

    <div>
   
        <p>두번째</p>
   
    </div>

    <p>세번째</p>
</body>

 

 

 

설명: 일반적은 function 앞에 변수나 객채가 있어야 불러 올수있지만 아래와 같은 방법도 가능하다.

 

 

<script type="text/javascript">
(function(){
    // 익명함수를 구성 하고 호출 하는 방법
    alert("안녕하세요");
})();
    // 익명 함수 를 바로 출력 하기 위에서는 뒤에 펑션을 ()로 한번 묶고  (); 를 붙이면 가능 하다.
   
(function(name){
    // 익명함수를 구성 하고 호출 하는 방법
    alert(name+"씨 안녕하세요");
})("홍길동");
   
</script>
</head>
<body>
    <p>첫번째</p>

    <div>

        <p>두번째</p>

    </div>

    <p>세번째</p>
</body>

 

 

설명 : 기존에 사용 하는 jQuery 가 아닌 script 에서 (프로토 타입등.. ) $ 가 애칭등으로 사용된 경우 이후 jQuery를 사용 하는 경우 애칭이 사용이 안된다.이를 위해$을 애칭으로의 사용을 막는 것이다.

 

<script type="text/javascript">
jQuery.noConflict();// 이 명령 이후에는 jQuery 대신 $ 를 사용 할수 없다.

(function($){
    // 이 영역에서는 jQuery 대신 $를 사용 할수 있다.
    $(function(){
    alert($($("p").get(1)).text());
    });
    alert("안녕하세요");
})(jQuery);
</script>
</head>
<body>
    <p>첫번째</p>

    <div>

        <p>두번째</p>

    </div>

    <p>세번째</p>
</body>

위와 같다. 하지만 계속 $ 아닌 jQuery 를 사용 하는것은 불편 함으로 아래와 같이 적용 하자.

 

<script type="text/javascript">
    var $j = jQuery.noConflict();
    // jQuery 의 애칭인 $ 을 $j 로 변경 한것./ 제이쿼리의 애칭 사용을 금지 하고 제이쿼리객체를 돌려 준다.

    $j(function() {
        alert($j($j("p")[1]).text());
    });
</script>
</head>
<body>
    <p>첫번째</p>

    <div>

        <p>두번째</p>

    </div>

    <p>세번째</p>
</body>

 

 

 

 

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

3일차 export/change  (0) 2012.05.08
2일차 Selectors  (0) 2012.05.08
16일차 우편번호검색(json)  (0) 2012.05.08
16일차 select(DBMS:JSON:)  (0) 2012.05.08
15일차 DB->JSON(포멧 하기)  (0) 2012.05.08
Posted by 사라링

zip.jpg

 

 

 

SELECT ZIPCODE, SIDO, GUGUN, DONG, RI, BLDG, BUNJI, SEQ FROM ZIPTB ;

 

제약조건:

PK_ZIPTB    Primary_Key   
SYS_C004141    Check    "ZIPCODE" IS NOT NULL
SYS_C004142    Check    "SIDO" IS NOT NULL
SYS_C004143    Check    "GUGUN" IS NOT NULL
SYS_C004144    Check    "DONG" IS NOT NULL
SYS_C004145    Check    "SEQ" IS NOT NULL

 

데이터

ZIPCODE, SIDO, GUGUN, DONG, RI, BLDG, BUNJI, SEQ

135-806    서울    강남구    개포1동        경남아파트        1
135-807    서울    강남구    개포1동        우성3차아파트    (1∼6동)    2
135-806    서울    강남구    개포1동        우성9차아파트    (901∼902동)    3
135-770    서울    강남구    개포1동        주공아파트    (1∼16동)    4
135-805    서울    강남구    개포1동        주공아파트    (17∼40동)    5
135-966    서울    강남구    개포1동        주공아파트    (41∼85동)    6
135-807    서울    강남구    개포1동        주공아파트    (86∼103동)    7
135-805    서울    강남구    개포1동        주공아파트    (104∼125동)    8
135-807    서울    강남구    개포1동        현대1차아파트    (101∼106동)    9
135-805    서울    강남구    개포1동            565    10
135-806    서울    강남구    개포1동            649∼651    11
135-807    서울    강남구    개포1동            652∼653    12
135-810    서울    강남구    개포1동            660    13
135-241    서울    강남구    개포1동                14
135-800    서울    강남구    개포2동        우성8차아파트    (801∼803동)    15

 

 

SimpleZip.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SimpleZip</title>
<script type="text/javascript" src="../../js/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function(){
        $("#zipBtn").click(function(){
        win =window.open("zipSc2.jsp","우편번호","scrollbars=yes, width=450, height=300, resizable=yes, menubar=no, top=150, left=260");
            return true;
        });
       
    });

</script>


</head>
<body>
   
<table border=1>
<form name="zipform" action="save.jsp" method="post">
<tr><td>성명</td><td><input type="text" name="irum" size=12></td></tr>
<tr><td>우편번호</td><td><input type=text name="zip1" size=3 readonly>  -
<input type=text name="zip2" size=3 readonly>
<input type="button" name="zip" value="우편번호검색" id="zipBtn"></td></tr>
<tr><td>주소</td><td><input type=text name="address" size=30></td></tr>
<tr><td>전화번호</td>
<td> <input type=text name=tel1 size=5>-<input type=text name=tel2 size=5>-<input type=text name=tel3 size=5></td>
</tr>
<tr><td><input type=submit value=Save>   <input type=reset value=Reset> </td></tr>
</table>
</form>


</body>
</html>

 

zipSc2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/plain; charset=UTF-8" />
<title>우편 검색</title>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/main.css" />
<script type="text/javascript" src="../../js/jquery-1.7.2.js"></script>
<script type="text/javascript">
/* function parent(d){
    alert(d);
    var v = val.value;

    if(!opener) return;
   
  } */
  function myClick(){
      alert(눌렀다);
/*        var tb = document.getElementById("tb");

       alert(tb.rows[1].cells[4].innerText);
   */
  };
     $(function(){
         $("#list tr").live("click",function(){
        
             var  zipsp=$(this,"td").eq(0).text();
             //alert(zipsp);
             var zipsp2 = zipsp.split("-");
             var zipfirst=zipsp2[0];
             var zipsp3=zipsp2[1].split(":");
             //alert(zipsp3[0]);
             var ziplast=zipsp3[0];
             var addfinal = zipsp3[1];
             opener.document.zipform.zip1.value=zipfirst;
             opener.document.zipform.zip2.value=ziplast;
             opener.document.zipform.address.value=addfinal;
             self.closed();
            
        
         });
        $("#zipBtnDB").click(function(){
            //alert("눌렀따");
           
            var dong=$.trim($("#zipDBSC").val());
            if(dong==null||dong==""){
                alert("동이름을 입력해주세요.");
                return;
            }
           
            $.ajax({
                "url" : "zipSc3.jsp",
                "type" : "get",
                "dataType": "json",
                "data" : {"dong":dong},
                "success" : function(data){
                    var str = "<table border='1' bordercolor='blue'>";
                    str +="<tr >";
                    $.each(data,function(i,v){
                        str +="<td>"+v.zipcode +":</td>";
                        str +="<td>"+v.sido +" ";
                        str +=v.gugun +" ";
                        str +=v.dong +" ";
                        str +=v.ri +" ";
                        str +=v.bldg +" ";
                        str +=v.bunji +" ";
                        str +="</td></tr>";
                    });
                    str +="</table>";
                    $("#list").html(str);
                   
                },
                "error" : function(info, xhr){
                    if(info.readyState == '4'){
                     alert('문제가 발생했습니다.\n상태코드 : ' + info.status+ '\n\n' + info.responseText);
                    }
                    else{
                     alert('문제가 발생했습니다.\n잠시후 다시 시도해 주세요.\n 상태코드 : ' +info.status);
                    }
                   }
            });
             
           
/*              $.getJSON(
                "zipSc3.jsp",
                "lowAdd="+lowAdd,
                function(data){
                    alert(data);
                    var str = "<table border='1' bordercolor='blue'>";
                    $.each(data,function(i,v){
                        str +="<tr><td>"+(i+1)+"번</td> ";
                        str +="<td>"+v.zipcode +" </td>";
                        str +="<td>"+v.sido +" ";
                        str +=v.gugun +" ";
                        if(v.ri   !=null)str +=+v.ri +" ";
                        if(v.bldg !=null)str +=+v.bldg +" ";
                        if(v.bunji!=null)str +=+v.bunji +" ";
                        str +="</td></tr>";
                    });
                    str +="</table>";
                    $("#showZip").html(str);
                }
            );  */
           
        });
    });
</script>

</head>
<body>
<table>
<tr>
    <td>동검색</td><td><input type="text" id="zipDBSC" size="8" /> ex) '대흥동'
    <input type="button" id="zipBtnDB" value="검색"/></td>
</tr>

</table>


<div id="list" class="zipList">

</div>




</body>
</html>

zipSc3.jsp

<%@page import="kr.or.ddit.db.*"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/plain; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8");

    String dong =request.getParameter("dong");
%>    
<%
    
Connection conn= null;
    PreparedStatement psmt= null;
    ResultSet rs = null;
    
    

try{
    conn = ConnectionProvider.getConnection();
    psmt = conn.prepareStatement("SELECT ZIPCODE, SIDO, GUGUN, DONG, RI, BLDG, BUNJI, SEQ FROM ZIPTB where dong like ?");
    psmt.setString(1, "%"+dong+"%");
    rs= psmt.executeQuery();

%>
[
    <%while(rs.next()){
    if(rs.getRow()>1){
        out.print(",");
    }
    %>
{
    "zipcode" : "<%=Util.toJS(rs.getString("zipcode")) %>",
    "sido"    : "<%=Util.toJS(rs.getString("sido"))%>",
    "gugun"   : "<%=Util.toJS(rs.getString("gugun"))%>",
    "dong"    : "<%=Util.toJS(rs.getString("dong"))%>",
    "ri"      : "<%=Util.toJS(rs.getString("ri"))%>",
    "bldg"    : "<%=Util.toJS(rs.getString("bldg"))%>",
    "bunji"   : "<%=Util.toJS(rs.getString("bunji"))%>"
}
<%
}%>
]
<%
}catch(SQLException e){
    e.printStackTrace();
}finally{
if(rs!=null) try{rs.close();}catch(Exception e){}
if(psmt!=null) try{psmt.close();}catch(Exception e){}
if(conn!=null) try{conn.close();}catch(Exception e){}
}
%>

 

Util.java (데이터 포멧)

package kr.or.ddit.db;

public class Util {

    public static String toJS(String str){
        if(str==null) return "";
        return str.replace("\\", "\\\\")
                  .replace("\"","\\\"")
                  .replace("\'","\\\'")
                  .replace("\r\n","\\n")
                  .replace("\n","\\n");
    }
   
}

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

2일차 Selectors  (0) 2012.05.08
1일차 get/function  (0) 2012.05.08
16일차 select(DBMS:JSON:)  (0) 2012.05.08
15일차 DB->JSON(포멧 하기)  (0) 2012.05.08
11일차 Ajax2  (0) 2012.05.08
Posted by 사라링

16일차 select(DBMS:JSON:)

2012. 5. 8. 18:23

sel.jpg

 

DB LPROD

 

  • LPROD_ID
  • LPROD_GU
  • LPROD_NM

 

1    P101    computer
2    P102    electronic
3    P201    womancasual
4    P202    남성캐주얼
5    P301    etcbrand
6    P302    cosmetic
7    P401    record/CD
8    P402    book
9    P403    stationery
15    p203    아동복

 

DB PROD

 

  • PROD_ID
  • PROD_NAME
  • PROD_LGU
  • PROD_BUYER
  • PROD_COST
  • PROD_PRICE
  • PROD_SALE
  • PROD_OUTLINE
  • PROD_DETAIL
  • PROD_IMG
  • PROD_TOTALSTOCK
  • PROD_INSDATE
  • PROD_PROPERSTOCK
  • PROD_SIZE
  • PROD_COLOR
  • PROD_DELIVERY
  • PROD_UNIT
  • PROD_QTYIN
  • PROD_QTYSALE
  • PROD_MILEAGE

 

P101000001    모니터 삼성전자15인치칼라    P101    P10101    210000    290000    230000    평면모니터의 기적    우리기술의 개가
P101000002    모니터 삼성전자17인치칼라    P101    P10101    310000    390000    330000    평면모니터의 기적    우리기술의 개가
P101000003    모니터 삼성전자19인치칼라    P101    P10101    410000    490000    430000    평면모니터의 기적    우리기술의 개가
P101000004    삼보컴퓨터 P-III 600Mhz    P101    P10102    1150000    1780000    1330000    쉬운 인터넷을.....    새로운 차원의 컴퓨터를.....
P101000005    삼보컴퓨터 P-III 700Mhz    P101    P10102    2150000    2780000    2330000    쉬운 인터넷을.....    새로운 차원의 컴퓨터를.....
P101000006    삼보컴퓨터 P-III 800Mhz    P101    P10102    3150000    3780000    3330000    쉬운 인터넷을.....    새로운 차원의 컴퓨터를.....
P102000001    대우 칼라 TV 25인치    P102    P10201    690000    820000    720000    집안에 영화관을.....    평면 브라운관의 새장.....
P102000002    대우 칼라 TV 29인치    P102    P10201    890000    1020000    920000    집안에 영화관을.....    평면 브라운관의 새장.....
P102000003    삼성 칼라 TV 21인치    P102    P10202    590000    720000    620000    집안에 영화관을.....    평면 브라운관의 새장.....
P102000004    삼성 칼라 TV 29인치    P102    P10202    990000    1120000    1020000    집안에 영화관을.....    평면 브라운관의 새장.....
P102000005    삼성 칼라 TV 53인치    P102    P10202    1990000    2120000    2020000    집안에 영화관을.....    평면 브라운관의 새장.....
P102000006    삼성 캠코더    P102    P10202    660000    880000    770000    가족과 영화촬영을.....    레저와 함께.....
P102000007    대우 VTR 6헤드    P102    P10201    550000    760000    610000    선명한 화질    감동의 명화를.....
P201000001    여성 봄 셔츠 1    P201    P20101    21000    42000    27000    파릇한 봄을 위한    아름다운.....
P201000002    여성 봄 셔츠 2    P201    P20101    22000    43000    28000    파릇한 봄을 위한    아름다운.....
P201000003    여성 봄 셔츠 3    P201    P20101    23000    44000    29000    파릇한 봄을 위한    아름다운.....
P201000004    여성 여름 셔츠 1    P201    P20101    12000    21000    25000    시원한 여름을 위한    아름다운.....
P201000005    여성 여름 셔츠 2    P201    P20101    13000    22000    26000    시원한 여름을 위한    아름다운.....
P201000006    여성 여름 셔츠 3    P201    P20101    14000    23000    27000    시원한 여름을 위한    아름다운.....
P201000007    여성 겨울 라운드 셔츠 1    P201    P20101    31000    45000    33000    따뜻한 겨울을 위한    아름다운.....
P201000008    여성 겨울 라운드 셔츠 2    P201    P20101    32000    46000    34000    따뜻한 겨울을 위한    아름다운.....
P201000009    여성 겨울 라운드 셔츠 3    P201    P20101    33000    47000    35000    따뜻한 겨울을 위한    아름다운.....
P201000010    여성 청바지 1    P201    P20102    55000    66000    57000    편리한 활동파를 위한    편리한.....
P201000011    여성 청바지 2    P201    P20102    56000    67000    58000    편리한 활동파를 위한    편리한.....
P201000012    여성 청바지 3    P201    P20102    57000    68000    59000    편리한 활동파를 위한    편리한.....
P201000013    여성 봄 자켓 1    P201    P20101    110000    210000    170000    편리한 활동파의 봄을 위한    아름다운.....
P201000014    여성 봄 자켓 2    P201    P20101    120000    220000    180000    편리한 활동파의 봄을 위한    아름다운.....
P201000015    여성 봄 자켓 3    P201    P20101    130000    230000    190000    편리한 활동파의 봄을 위한    아름다운.....
P201000016    여성 여름 자켓 1    P201    P20102    100000    160000    130000    편리한 활동파의 여름을 위한    아름다운.....
P201000017    여성 여름 자켓 2    P201    P20102    110000    170000    140000    편리한 활동파의 여름을 위한    아름다운.....
P201000018    여성 여름 자켓 3    P201    P20102    120000    180000    150000    편리한 활동파의 여름을 위한    아름다운.....
P201000019    여성 겨울 자켓 1    P201    P20102    210000    270000    240000    편리한 활동파의 따뜻한 겨울을 위한    아름다운.....
P201000020    여성 겨울 자켓 2    P201    P20102    220000    280000    250000    편리한 활동파의 따뜻한 겨울을 위한    아름다운.....
P201000021    여성 겨울 자켓 3    P201    P20102    230000    290000    260000    편리한 활동파의 따뜻한 겨울을 위한    아름다운.....
P202000001    남성 봄 셔츠 1    P202    P20201    10000    19000    15000    파릇한 봄을 위한    아름다운.....
P202000002    남성 봄 셔츠 2    P202    P20201    13000    22000    18000    파릇한 봄을 위한    아름다운.....
P202000003    남성 봄 셔츠 3    P202    P20201    15000    24000    20000    파릇한 봄을 위한    아름다운.....
P202000004    남성 여름 셔츠 1    P202    P20201    18000    28000    23000    시원한 여름을 위한    아름다운.....
P202000005    남성 여름 셔츠 2    P202    P20201    23000    33000    28000    시원한 여름을 위한    아름다운.....

...... 등등

 

 

lprod.jsp (main)

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>lprod main</title>
<script type="text/javascript" src="../../js/jquery-1.7.2.js"></script>
<script type="text/javascript">

/*
lprod_gu
lprod_nm

<option value="">내용</option>
 */
 
     function prodchange(){
     var prod_id="";
     $("select[name='prod'] option:selected").each(function(){
         prod_id+=$(this).val();
     });
     alert(prod_id);
      $.getJSON(
        "lpdata3.jsp",
        "prod_id="+prod_id,
        function(data){
            var str = "<table border='1' bordercolor='blue' align='center'>";
            $.each(data,function(i,v){
                str +="<tr><th>prod_id     </th><td>"+v.prod_id     +"</td></tr>";
                str +="<tr><th>prod_name   </th><td>"+v.prod_name   +"</td></tr>";
                str +="<tr><th>prod_buyer  </th><td>"+v.prod_buyer  +"</td></tr>";
                str +="<tr><th>prod_cost   </th><td>"+v.prod_cost   +"</td></tr>";
                str +="<tr><th>prod_price  </th><td>"+v.prod_price  +"</td></tr>";
                str +="<tr><th>prod_sale   </th><td>"+v.prod_sale   +"</td></tr>";
                str +="<tr><th>prod_outline</th><td>"+v.prod_outline+"</td></tr>";
                str +="<tr><th>prod_detail </th><td>"+v.prod_detail +"</td></tr>";
            });
            str +="</table>";
            $("#prodDetail").html(str);
/*            
prod_id    
prod_name  
prod_buyer 
prod_cost  
prod_price 
prod_sale  
prod_outline
prod_detail    


           
           
           
 */           
        }
    ); 
     
 
 
     }
 
     function lprodChange(){
     var gu="";
     $("select[name='lprod'] option:selected").each(function(){
         gu+=$(this).val();
         //gu=$(this).eq(0).val();
     });
      $.getJSON(
        "lpdata2.jsp",
        "gu="+gu,
        function(data){
            var str = "";
            $.each(data,function(i,v){
            str +="<option value='"+v.prod_id+"'>"+v.prod_name+"</option><br>";
            });
           
            $("#prod").html(str);
        }
    ); 
 }
 
 
    $(function(){
       
        $("select[name='prod']").change(prodchange);
        $("select[name='lprod']").change(lprodChange);

/*         $.ajax({
            "url" : "lpdata1.jsp",
            "dataType": "json",
            "success" : function(data){
                alert(data);
                var str = "";
                $.each(data,function(i,v){
                    str +="<option value="+v.lprod_gu+">"+v.lprod_nm"</option>";
                });
                str +="</option>";
                $("#lprod").html(str);
               
            },
            "error" : function(info, xhr){
                if(info.readyState == '4'){
                 alert('문제가 발생했습니다.\n상태코드 : ' + info.status+ '\n\n' + info.responseText);
                }
                else{
                 alert('문제가 발생했습니다.\n잠시후 다시 시도해 주세요.\n 상태코드 : ' +info.status);
                }
               }
        }); */
         $.getJSON(
                "lpdata1.jsp",
                function(data){
                    var str = "";
                    $.each(data,function(i,v){
                    str +="<option value='"+v.lprod_gu+"'>"+v.lprod_nm+"</option>";
                    });
                    $("#lprod").html(str);
                }
        );
   
       
       
       
    });
</script>


</head>
<body>

<form action="testForm">
<table align="center">
    <tr>
        <td>
            <select name ="lprod" id="lprod">
           
            </select>
       
        </td>
       
        <td width="50">&nbsp;</td>
        <td>   
            <select name="prod" id="prod">
           
           
            </select>
        </td>
    </tr>
</table>
</form>
<div id="prodDetail"></div>

</body>
</html>

lpdata1.jsp

<%@page import="kr.or.ddit.db.*"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/plain; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8");

%>   
<%
   
    Connection conn= null;
    PreparedStatement psmt= null;
    ResultSet rs = null;
   
   

try{
    conn = ConnectionProvider.getConnection();
    psmt = conn.prepareStatement("SELECT LPROD_GU, LPROD_NM FROM LPROD");
    rs= psmt.executeQuery();

%>
[
    <%while(rs.next()){
    if(rs.getRow()>1){
        out.print(",");
    }
    %>
{
   
    "lprod_gu"  : "<%=Util.toJS(rs.getString("lprod_gu"))%>",
    "lprod_nm"  : "<%=Util.toJS(rs.getString("lprod_nm"))%>"

}
<%
}%>
]
<%
}catch(SQLException e){
    e.printStackTrace();
}finally{
if(rs!=null) try{rs.close();}catch(Exception e){}
if(psmt!=null) try{psmt.close();}catch(Exception e){}
if(conn!=null) try{conn.close();}catch(Exception e){}
}
%>

lpdata2.jsp

<%@page import="kr.or.ddit.db.*"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/plain; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8");

%>   
<%
    String gu = request.getParameter("gu");
    Connection conn= null;
    PreparedStatement psmt= null;
    ResultSet rs = null;

   

try{
    conn = ConnectionProvider.getConnection();
    psmt = conn.prepareStatement("select prod_id, prod_name from prod where prod_lgu=?");
    psmt.setString(1, gu);
    rs= psmt.executeQuery();

%>
[
    <%while(rs.next()){
    if(rs.getRow()>1){
        out.print(",");
    }
    %>
{
   
    "prod_id"  : "<%=Util.toJS(rs.getString("prod_id"))%>",
    "prod_name"  : "<%=Util.toJS(rs.getString("prod_name"))%>"

}
<%
}%>
]
<%
}catch(SQLException e){
    e.printStackTrace();
}finally{
if(rs!=null) try{rs.close();}catch(Exception e){}
if(psmt!=null) try{psmt.close();}catch(Exception e){}
if(conn!=null) try{conn.close();}catch(Exception e){}
}
%>

lpdata3.jsp

<%@page import="kr.or.ddit.db.*"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/plain; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8");

%>   
<%
    String prod_id =request.getParameter("prod_id");
    Connection conn= null;
    PreparedStatement psmt= null;
    ResultSet rs = null;

try{
    conn = ConnectionProvider.getConnection();
    psmt = conn.prepareStatement("select prod_id, prod_name,prod_buyer,prod_cost,prod_price,prod_sale,prod_outline,prod_detail from prod where prod_id=?");
    psmt.setString(1, prod_id);
    rs= psmt.executeQuery();

%>
[
    <%while(rs.next()){
    if(rs.getRow()>1){
        out.print(",");
    }
    %>
{
   
    "prod_id"  : "<%=Util.toJS(rs.getString("prod_id"))%>",
    "prod_name"  : "<%=Util.toJS(rs.getString("prod_name"))%>",
    "prod_buyer"  : "<%=Util.toJS(rs.getString("prod_buyer"))%>",
    "prod_cost"  : "<%=Util.toJS(rs.getString("prod_cost"))%>",
    "prod_price"  : "<%=Util.toJS(rs.getString("prod_price"))%>",
    "prod_sale"  : "<%=Util.toJS(rs.getString("prod_sale"))%>",
    "prod_outline"  : "<%=Util.toJS(rs.getString("prod_outline"))%>",
    "prod_detail"  : "<%=Util.toJS(rs.getString("prod_detail"))%>"

}
<%
}%>
]
<%
}catch(SQLException e){
    e.printStackTrace();
}finally{
if(rs!=null) try{rs.close();}catch(Exception e){}
if(psmt!=null) try{psmt.close();}catch(Exception e){}
if(conn!=null) try{conn.close();}catch(Exception e){}
}
%>

 

Util.java (format 용)

package kr.or.ddit.db;

public class Util {

    public static String toJS(String str){
        if(str==null) return "";
        return str.replace("\\", "\\\\")
                  .replace("\"","\\\"")
                  .replace("\'","\\\'")
                  .replace("\r\n","\\n")
                  .replace("\n","\\n");
    }
   
}

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

1일차 get/function  (0) 2012.05.08
16일차 우편번호검색(json)  (0) 2012.05.08
15일차 DB->JSON(포멧 하기)  (0) 2012.05.08
11일차 Ajax2  (0) 2012.05.08
-1일차 css셋팅  (0) 2012.05.08
Posted by 사라링

<%@ page language="java" contentType="text/plain; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>   
<%
    String str = "안녕하세요 \n '홍길동' 입니다. ";

%>
{
    "insa" : '<%=str %>'
}

이러한 데이터를 출력 하면 잘못 나온다.

 잘못된표현.jpg

 

이것을 옳바르게 바꾸기 위해선 insa2 와 같이 만들어야 하는데. static 한 메서드를 만들어야 한다.

 

public class Util {

    public static String toJS(String str){
        if(str==null) return "";
        return str.replace("\\", "\\\\")
                  .replace("\"","\\\"")
                  .replace("\'","\\\'")
                  .replace("\r\n","\\n")
                  .replace("\n","\\n");
    }
   
}

이러한 클래스를 만들어서

 

jsp 소스 중간에 "insa2" : '<%=Util.toJS(str) %>'  를 포함 시키면 아래와 같이 insa2 가 출력이 되며 JSON 표기법 사용이 가능 하다.

 

옳은것.jpg

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

16일차 우편번호검색(json)  (0) 2012.05.08
16일차 select(DBMS:JSON:)  (0) 2012.05.08
11일차 Ajax2  (0) 2012.05.08
-1일차 css셋팅  (0) 2012.05.08
J-쿼리  (0) 2012.05.08
Posted by 사라링

11일차 Ajax2

2012. 5. 8. 18:23

 

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

16일차 우편번호검색(json)  (0) 2012.05.08
16일차 select(DBMS:JSON:)  (0) 2012.05.08
15일차 DB->JSON(포멧 하기)  (0) 2012.05.08
-1일차 css셋팅  (0) 2012.05.08
J-쿼리  (0) 2012.05.08
Posted by 사라링

-1일차 css셋팅

2012. 5. 8. 18:22



 

 아직은 기초를 배우고 있지만 포인트는 $( )구문을 이용해서 내가 적용하고자하는 객체를 찾아 갈수 있다.

 

<?xml version="1.0" encoding="EUC-KR" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR" />
<title>Insert title here</title>

 

<!--  css 셋팅 -->

<link type="text/css" href="css/custom-theme/jquery-ui-1.8.17.custom.css" rel="stylesheet" /> 
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script>

 

<script type="text/javascript">
function color(){
 $('.list').css("backgroundColor",'yellow');
 
 
}
function odd(){
 $(".list>li:odd").css("background-color" , "#bbbbff" ).css("border" ," thick pink dotted " );
  
}

function even(){
 $(".list>li:not(:odd)").css("background-color" , "#bbbbff" ).css("border" ," thick pink dotted " );
  
}

function bokyoung(){
 $(".list>li:gt(2)").hide(2000);
 
 
}
function ja(){
 for(var i =0 ; i <100 ; i++){
 $(".jasik>ol").css("background-color" , "#bbbbff" ).fadeIn(2000);
 $(".jasik>ol").css("background-color" , "#bbbbff" ).fadeOut(1000);
 }
 
}

function ground(){
  $('.list > li ').animate({"background-color":"white","width":500},5000).hide(5000);
}
/*
 앞에다가 $(document).ready를 함수앞에다가 안써도 상관은 없지만
 나중에 많아지면 중첩에 문제가 생길수 있기때문에 꼭 쓰는것을 추천한다!!
 $(document).ready(function() { 내용 }) ;

  : first(첫번째것) :last (마지막것)
  : contains(문자열)(문자열을 포함하는것),
  : empty(내용이 없는것), :has(선택자)(선택자를 가진것),
  : parent(부모)
  : hidden(숨겨진 것), :visible(보이는 것),
  : not(선택자)(선택자가 아닌것)
  : gt(index)(보다큰것)  :lt(index)(보다작은것)

*/


</script>

</head>
<body>
<ol class="list" >
 <input type="button" value="배경노랑색으로!!" onclick = "color()" />
 <input type="button" value="없어져라 야삐!!" onclick = "ground()" />
 <input type="button" value="짝수만!!!" onclick = "even()" />
 <input type="button" value="홀수만사라져라!!" onclick = "odd()" />
 <input type="button" value="복영밑으로사라져!" onclick = "bokyoung()" />
 <input type="button" value="자식디져라!!!" onclick = "ja()" />
 
 <li class="jasik">최강채광0
  <ol>
   <li>야호</li>
   <li>야호~!!</li>
  </ol>
 </li>
 <li>쓰담지연1</li>
 <li>꽐라준영2</li>
 <li>어깨복영3</li>
 <li>봉긋형석4</li>
 <li>야하!!쿄5</li>

</ol>

</body>

</html>

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

16일차 우편번호검색(json)  (0) 2012.05.08
16일차 select(DBMS:JSON:)  (0) 2012.05.08
15일차 DB->JSON(포멧 하기)  (0) 2012.05.08
11일차 Ajax2  (0) 2012.05.08
J-쿼리  (0) 2012.05.08
Posted by 사라링

BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
디자인패턴 (1)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
웹스퀘어_ (0)
Total :
Today : Yesterday :