출처: http://srchun.springnote.com/pages/4799503

브라우저 별로 크기가 다르다는 얘기..

scrollHieght 찾다가 나왔음...
        var el = document.createElement("span");
        el.setAttribute("title", key);
        el.setAttribute("class", "dpCatLabel");
      //el.setAttribute("onclick", "alert('TEST');"); // DOESN'T WORK. onclick is not attribute.
      el.onclick=function(){alert("TEST");};
        var txt = document.createTextNode(label);
        el.appendChild(txt);

onclick 등은 이벤트라서 setAttribute로 붙일 수 없고,
el.onclick=function;  으로 붙이자.

[jQuery] jQuery를 이용한 ajax

프로그래밍/Web 2009. 12. 16. 11:20 Posted by galad
function ajaxGetDpCatList() {
    //alert("ajax로 전체 전시 카테고리 정보 얻기");
    //alert($(this).attr("title"));
   
    var selectedCatId = $(this).attr("title");
    $("#selectedCatId").val(selectedCatId);
    //alert($("#selectedCatId").val());
   
    $.ajax({
        url: '${pageContext.request.contextPath}/categoryMapping/getDpCatList.omp',
        type: 'POST',
        dataType: 'json',
        timeout: 5000,
        error: function(){
            alert('전시 카테고리 정보를 얻는 중에 오류가 발생했습니다.');
        },
        success: function(data){
            //alert(data);
            //alert(data.dpCatList[0].key + " " + data.dpCatList[0].value);
            showDpCatList(data);
        }
    });
}

- json 형식으로 결과를 받겠다 해놓고, 결과가 json형식에 안맞아도 error.
- timeout 시간이 넘어가도 error. 처음엔 개발장비서 할 떄 계속 에러나서 원인을 못찾았었음. 주의할 것.

$.ajax외에도 $.post 같은 좀 더 간단한 jQuery 메소드가 있음.
http://www.ibm.com/developerworks/kr/library/wa-jquery3/

[javascript] HTML DOM 지우기

프로그래밍/Web 2009. 12. 16. 10:25 Posted by galad
createElement로 생성한 노드들을 지울때, 특정 노드 밑에 딸린 노드들을 몽창 한번에 지우는 메소드가 없는 건지 못찾은 건지,
아무튼 parentNode에 딸린 노드들을 전부 찾아서(getElementsByTag), for 루프 돌면서 지우는데 절반만 지워져서 헤매다가 원인을 찾았음

function deleteNodes(parentNode, tag) {
    var nodes = parentNode.getElementsByTagName(tag);
    var length = nodes.length;
    
    // 이건 nodes가 실시간으로 줄어들면서 length 자체가 줄어든다.
    // 따라서 아래의 for문에서 기존 nodes의 갯수만큼 루핑하면서 0번만 계속 지움.
    // i번을 삭제하면 stack overflow 남
    /*for(var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        parentNode.removeChild(node);
    }*/
    
    for(var i = 0; i < length; i++) {
        var node = nodes[0];
        parentNode.removeChild(node);
    }
}

위에 써놓은 것처럼

for(var i = 0; i < nodes.length; i++) {
    var node = nodes[i];
    parentNode.removeChild(node);
}

nodes.length로 한계치를 정하면 for 문 안에서 자식 노드를 하나씩 지울 때마다 nodes.length 가 하나씩 줄어든다. 실시간 반영?!
그래서 length를 따로 저장하고 맨 처음 것만 계속 지웠음.

'프로그래밍 > Web' 카테고리의 다른 글

[javascript] HTML DOM 생성 후 이벤트 추가  (0) 2009.12.16
[jQuery] jQuery를 이용한 ajax  (0) 2009.12.16
[jQuery] jQuery를 이용한 팝업. div, layer  (0) 2009.12.16
[json] json 사용법  (0) 2009.12.15
[html] html 특수기호  (3) 2009.09.08
출처: http://whdrnr01.textcube.com/7?t=c&i=0

jQuery를 이용해서, div의 설정 변경을 통한 레이어 팝업.
ajax랑 함께 쓰면, ajax를 이용해서 데이터를 얻어온 후, div의 안에 원하는 형태로 데이터를 넣고 나서 보여주는 형식이 될 듯.

소스출처: http://yensdesign.com/tutorials/popupjquery/

/**
 * jQuery를 이용한 초기 설정
 */
$(document).ready(function() {
    // 마우스 오버 시 배경색 반전
    $(".catLabel1").hover(
        function() { // hover 시
            $(this).css({"background-color":"yellow", "font-weight":"bolder" });
        },
        function() { // out 시
            $(this).css({"background-color":"white", "font-weight":"normal" });
        }
    );

    $(".catLabel2").hover(
            function() { // hover 시
                $(this).css({"background-color":"yellow", "font-weight":"bolder" });
            },
            function() { // out 시
                $(this).css({"background-color":"white", "font-weight":"normal" });
            }
        );
   
    // 표준분류 선택 시 전시 카테고리 목록을 표시한다.
    $(".catLabel1").click(showAlert);
    $(".catLabel2").click(ajaxGetDpCatList);
   
    //CLOSING POPUP
    //Click the x event!
    /*$("#popupContactClose").click(function(){
        disablePopup();
    });*/
    //Click out event!
    $("#backgroundPopup").click(function(){
        disablePopup();
    });
    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 && popupStatus==1){
            disablePopup();
        }
    });
});

/**
 * 표준 분류의 대분류 선택 시 경고 메시지
 */
function showAlert() {
    alert("표준 카테고리의 중분류를 선택해 주세요.");
}

/**
 * ajax로 전시 카테고리 목록 얻어오기
 */
function ajaxGetDpCatList() {
    //alert("ajax로 전체 전시 카테고리 정보 얻기");
    //alert($(this).attr("title"));
   
    var selectedCatId = $(this).attr("title");
    $("#selectedCatId").val(selectedCatId);
    //alert($("#selectedCatId").val());
   
    $.ajax({
        url: '${pageContext.request.contextPath}/categoryMapping/getDpCatList.omp',
        type: 'POST',
        dataType: 'json',
        timeout: 5000,
        error: function(){
            alert('전시 카테고리 정보를 얻는 중에 오류가 발생했습니다.');
        },
        success: function(data){
            //alert(data);
            //alert(data.dpCatList[0].key + " " + data.dpCatList[0].value);
            showDpCatList(data);
        }
    });
}

/**
 * 전시 카테고리 목록 표시
 */
function showDpCatList(data) {
    //alert($("#selectedCatId").val());
    //alert(data.dpCatList.length);

    var dpCatListPopup = document.getElementById("dpCatListPopup");

    // dpCatListPopup 의 내용을 비움. 안하면 계속 늘어남
    deleteNodes(dpCatListPopup, "span");
    deleteNodes(dpCatListPopup, "br");

    // 전시 카테고리 표시용 목록 만들기
    var list = data.dpCatList;
    for(var i = 0; i < list.length; i++) {
        var key = list[i].key;
        var label = list[i].value;

        var el = document.createElement("span");
        el.setAttribute("title", key);
        el.setAttribute("class", "dpCatLabel");
        //el.setAttribute("onclick", "alert('TEST');"); // DOESN'T WORK. onclick is not attribute.
        el.onclick=function(){alert("TEST");};
        var txt = document.createTextNode(label);
        el.appendChild(txt);

        dpCatListPopup.appendChild(el);
        dpCatListPopup.appendChild(document.createElement("br"));
    }

    setPopupPosition();
    loadPopup();
}

function deleteNodes(parentNode, tag) {
    var nodes = parentNode.getElementsByTagName(tag);
    var length = nodes.length;
   
    // 이건 nodes가 실시간으로 줄어들면서 length 자체가 줄어든다.
    // 따라서 아래의 for문에서 기존 nodes의 갯수만큼 루핑하면서 0번만 계속 지움.
    // i번을 삭제하면 stack overflow 남
    /*for(var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        parentNode.removeChild(node);
    }*/
   
    for(var i = 0; i < length; i++) {
        var node = nodes[0];
        parentNode.removeChild(node);
    }
}

//0 means disabled; 1 means enabled;
var popupStatus = 0;

/**
 * set popup position
 */
function setPopupPosition(){
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.scrollHeight; //clientHeight;
    var popupHeight = $("#dpCatListPopup").height();
    var popupWidth = $("#dpCatListPopup").width();
   
    //centering
    $("#dpCatListPopup").css({
        "position": "absolute",
        "top": 0, //windowHeight/2-popupHeight/2,
        "left": windowWidth/2-popupWidth/2
    });

    //only need force for IE6
    $("#backgroundPopup").css({
        "height": windowHeight
    });
   
}

function loadPopup(){
    //loads popup only if it is disabled
    if(popupStatus==0){
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        $("#dpCatListPopup").fadeIn("slow");
        popupStatus = 1;
    }
}

function disablePopup(){
    //disables popup only if it is enabled
    if(popupStatus==1){
        $("#backgroundPopup").fadeOut("slow");
        $("#dpCatListPopup").fadeOut("slow");
       
        popupStatus = 0;
    }
}

setPopupPosition() 으로 위치 설정.
loadPopup() 으로 보이기
disablePopup() 으로 숨기기

backgroundPopup 랑 dpCatListPopup 는 div의 id.

'프로그래밍 > Web' 카테고리의 다른 글

[jQuery] jQuery를 이용한 ajax  (0) 2009.12.16
[javascript] HTML DOM 지우기  (0) 2009.12.16
[json] json 사용법  (0) 2009.12.15
[html] html 특수기호  (3) 2009.09.08
[servlet] servlet  (0) 2009.09.04

[json] json 사용법

프로그래밍/Web 2009. 12. 15. 11:23 Posted by galad
출처: http://mogaji.springnote.com/pages/314716

{"payCodeList":
        [
            {"key":"PD00290","value":"무료"},
            {"key":"PD00292","value":"기간정액제"}
        ]
}

key:value 쌍만으로는 안될때는 이런 식으로...

아래는 위의 출처 내용을 보관을 위해 발췌했음.

JSON은 무엇인가?

  1. JSON은 무엇인가?
    • 경량의 데이타 교환 포맷이다.
      > XML과 비교한다.
    • 간단한 포맷
      > 사람들을 위해 읽고 쓰기가 쉽다.
      > 기계들을 위해 분석과 생성이 쉽다.
    • JSON은 텍스트 포맷이다.
      > 언어에 독립적으로 프로그래밍된다.
      > 프로그래머들에게 잘 알려진 C,C++,C#,Java,JavaScript,Perl,Pyton을 포함하는 C와 유사한 언어로 모여서 사용된다.

  2. XML을 넘어 왜 JSON인가?
    • on-the-wire(선을 통한) 데이타 포맷인 XML보다 가볍고 빠르다.
    • JSON 오브젝트는 XML 데이타가 타입이 없는데 비해 타입을 가진다.
      > JSON types : string, number, array, boolean
      > XML 데이타는 모두 String 이다.
    • JavaScript 코드를 위해 Native 코드포맷이다.
      > Data는 사용자의 JavaScript코드 안에서 JSON 객체에 접근이 쉽다.
      XML 데이타가 해석과 장황한 DOM API를 통해 변수에 접근하는 것을 필요로 하는데 비해
      > 회수한 값들은 사용자의 자바스크립트 안의 객체속성에서 읽기가 쉽다.

  3. JSON은 어디에서 사용되는가?
    • 구성정보를 나타낸다.
    • 통신 프로토콜을 실행한다.

JSON Object

  1. JSON 구조
    • name/value 쌍으로 구성된다.
      > 여러가지의 언어들에서 object, record, struct, dictionary, hashtable, 키를 가지는 리스트, 배열집합 처럼 얻어진다.
    • 값들이 리스트는 순서가 있다.
      > 대부분의 언어들에서 array, vector, list, sequence 처럼 얻어진다.
    • JSON은 대부분의 지금의 언어를 통해 일반적인 데이타구조들이 지원된다.

  2. JSON Object 표기법
    • JSON Object는 name/value 쌍의 set은 순서가 없다.
    • JSON Object는 { 로 시작하고 } 로 끝난다.
    • 각각의 이름은 : 와 ,로 구분된 name/value 쌍의 형식을 따른다.

  3. JSON과 JavaScript
    • JSON은 JavaScript의 객체 문자 표기의 부분집합이다.
      > JSON은 JavaScript안에서 혼란스럽거나 야단스럽지 않게 사용될 수 있다.

  4. JSON Object 예제
     
    var myJSONObject = {"bindings": [
    {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
    {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
    {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
    ]
    };
    • 위의 예에서, JSON JavaScript 객체는 세개의 객체를 포함한 배열을 갖고있는, 각각은 "ircEvent","method","regex" 멤버들을 포함한 하나의 멤버 "bindings"를 포함하여 생성된다.
    • 멤버들은 점(.) 이나 그아래 지시자들로 회수 할수 있다.
       
      myJSONObject.bindings[0].method // "newURI"
  5. JavaScript 코드안에서 Text를 Object로 변환하기
     
    var myObject = eval('(' + myJSONtext + ')');
    • eval() 함수를 사용하여, JSON text를 JSON 객체로 변환한다.
      > eval()은 JavaScript 컴파일러에서 실행한다.
      > JSON은 JavaScript의 서브셋으로 적합하다. 컴파일러는 text를 정확하게 변환하고, 객체 구조를 만든다.

  6. 보안 & JSON Parser
    // Include http://www.json.org/json.js
    var myObject = myJSONtext.parseJSON();
    • eval()은 컴파일 할 수 있고, 어떤 JavaScript 프로그램에서도 실행된다. 그래서 보안 이슈들(cross-site scripting)을 가질 수 있다.
      > 소스를 신뢰할 수 있을때, eval()을 사용해라.
    • 보안이 염려될 때 - 소스를 신뢰할 수 없을때 - JSON parser를 사용하는게 낫다.
      > JSON parser는 JSON text를 승인할 수 있다. 그래서 좀더 안전하다.

  7. Object를 Text로 변환하기
     
    var myJSONText = myObject.toJSONString();
    • 사용자는 JSON 객체를 JSON text로 변환할 수 있다.
    • JSON은 주기적 데이타 구조를 지원하지 않는다.

      > Do not give cyclical structures to the JSON stringifier
      > 주기적 구조들을 JSON stringfier로 줄수 없다

Java 안에서의 JSON

  1. 자바 개발자를 위한 JSON Tools
    • Parser
      > JSON text 파일들을 해석하고, 그들을 자바 모델로 변환한다.
    • Renderer
      > 자바를 text로 표현하게 한다.
    • Serializer
      > 알기쉬운 POJO clusters를 JSON 표현으로 나열한다.
    • Validator
      > JSON 스키마를 사용하여 JSON 파일의 내용을 유효한지 체크한다.

  2. JSONObject 자바 클래스
    • JSONObject의 name/value 쌍의 집합은 순서가 없다.
    • put 메소드는 객체로 name/value쌍을 add 한다.
    • text들은 JSON syntax rules을 정확히 따른 toString 메소드에 의해 만들어진다.
       
      myString = new JSONObject().put("JSON", "Hello, World!").toString();
      // myString is {"JSON": "Hello, World"}

클라이언트와 서버사이드 양쪽에서 JSON 데이타를 주고 받는 방법

  1. 서버사이드에서 JSON 데이타를 생성하고 보내는 방법
    • JSONObject 자바 객체를 생성한다.
    • put 메소드를 사용하여 name/value 쌍을 add한다.
    • toString 메소드를 사용하여 String 타입으로 변환한다.
      그리고 "text/xml" 또는 "text/plain" 처럼 content-type과 함께 클라이언트로 보낸다.
       
      myString = new JSONObject().put("JSON",toString();
      // myString is {"JSON": "Hello, World"}
  2. 클라이언트 사이드에서 JSON 데이타를 받는 방법
    • JSON 데이타는 String 처럼 반환된다.
    • JavaScript 코드안에서 JSON 객체를 만들수 있게 eval()을 호출한다.
      > var JSONdata = eval(req.response.Text);
    • 사용자는 한번 JSON 객체를 가질수 있고, 객체의 속성들에 접근하기 위해 . 을 사용할 수 있다.
       
      var name = JSONdata.name;
      var address = JSONdata.addresses[3];
      var streetname = JSONdata.addresses[3].street;
    • 클라이언트 사이드에서 JSON 데이타를 생성하고 보내는 방법
    • JSON 자바스크립트 객체를 생성한다.
    • XMLHttpRequest객체의 open 메소드 안에 "POST" HTTO 메소드를 사용한다.
    • XMLHttpRequest객체의 send 메소드안에서 JSON 자바스크립트 객체를 패스한다.
       
      var carAsJSON = JSON.stringify(car);
      var url = "JSONExample?timeStamp=" + new Date().getTime();
      createXMLHttpRequest();
      xmlHttp.open("POST", url, true);
      xmlHttp.onreadystatechange = handleStateChange;
      xmlHttp.setRequestHeader("Content-Type",
      "application/x-www-form-urlencoded");
      xmlHttp.send(carAsJSON);
  3. 서버사이드에서 JSON 데이타를 받는 방법
    • String 타입처럼 JSON데이타를 읽는다.
    • string으로부터 JSONObject 자바객체를 생성한다.
       
      String json = readJSONStringFromRequestBody(request);
      //Use the JSON-Java binding library to create a JSON object in Java
      JSONObject jsonObject = null;
      try {
      jsonObject = new JSONObject(json);
      }
      catch(ParseException pe) {
      }

리소스들

  1. JSON 리소스들
    • Introducing JSON
    > http://www.json.org/
    • JSON in JavaScript
    > http://www.json.org/js.html
    • JSON in Java
    > http://www.json.org/java/index.html

참고문헌

문서에 대하여

최초작성자 : 난다
최초작성일 : 2007년 4월 17일
버전 : 0.1
문서이력 :

  • 2007년 4월 17일 난다 문서 최초 생성

    [출처] JSON|작성자 agileman


'프로그래밍 > Web' 카테고리의 다른 글

[javascript] HTML DOM 지우기  (0) 2009.12.16
[jQuery] jQuery를 이용한 팝업. div, layer  (0) 2009.12.16
[html] html 특수기호  (3) 2009.09.08
[servlet] servlet  (0) 2009.09.04
[jQuery] jQuery 예제 02  (0) 2009.09.04

[html] html 특수기호

프로그래밍/Web 2009. 9. 8. 10:13 Posted by galad
출처: http://blog.eloitcube.co.kr/35

HTML 특수문자코드표

표현문자

숫자표현

문자표현

설명

-

&#00;-&#08;

-

사용하지 않음

space

&#09;

-

수평탭

space

&#10;

-

줄 삽입

-

&#11;-&#31;

-

사용하지 않음

space

&#32;

-

여백

!

&#33;

-

느낌표

"

&#34;

&quot;

따옴표

#

&#35;

-

숫자기호

$

&#36;

-

달러

%

&#37;

-

백분율 기호

&

&#38;

&amp;

Ampersand

'

&#39;

-

작은 따옴표

(

&#40;

-

왼쪽 괄호

)

&#41;

-

오른쪽 괄호

*

&#42;

-

아스트릭

+

&#43;

-

더하기 기호

,

&#44;

-

쉼표

-

&#45;

-

Hyphen

.

&#46;

-

마침표

/

&#47;

-

Solidus (slash)

0 - 9

&#48;-&#57;

-

0부터 9까지

:

&#58;

-

콜론

;

&#59;

-

세미콜론

<

&#60;

&lt;

보다 작은

=

&#61;

-

등호

>

&#62;

&gt;

보다 큰

?

&#63;

-

물음표

@

&#64;

-

Commercial at

A - Z

&#65;-&#90;

-

A부터 Z까지

[

&#91;

-

왼쪽 대괄호

\

&#92;

-

역슬래쉬

]

&#93;

-

오른쪽 대괄호

^

&#94;

-

탈자부호

_

&#95;

-

수평선

`

&#96;

-

Acute accent

a - z

&#97;-&#122;

-

a부터 z까지

{

&#123;

-

왼쪽 중괄호

|

&#124;

-

수직선

}

&#125;

-

오른쪽 중괄호

~

&#126;

-

꼬리표

-

&#127;-&#159;

-

사용하지 않음


&#160;

&nbsp;

Non-breaking space

¡

&#161;

&iexcl;

거꾸로된 느낌표

&#162;

&cent;

센트 기호

&#163;

&pound;

파운드

¤

&#164;

&curren;

현재 환율

&#165;

&yen;

|

&#166;

&brvbar;

끊어진 수직선

§

&#167;

&sect;

섹션 기호

¨

&#168;

&uml;

움라우트

&#169;

&copy;

저작권

ª

&#170;

&ordf;

Feminine ordinal

&#171;

&laquo;

왼쪽 꺾인 괄호

&#172;

&not;

부정


&#173;

&shy;

Soft hyphen

?

&#174;

&reg;

등록상표

&hibar;

&#175;

&macr;

Macron accent

°

&#176;

&deg;

Degree sign

±

&#177;

&plusmn;

Plus or minus

²

&#178;

&sup2;

Superscript two

³

&#179;

&sup3;

Superscript three

´

&#180;

&acute;

Acute accent

μ

&#181;

&micro;

Micro sign (Mu)

&#182;

&para;

문단기호

·

&#183;

&middot;

Middle dot

¸

&#184;

&cedil;

Cedilla

¹

&#185;

&sup1;

Superscript one

º

&#186;

&ordm;

Masculine ordinal

&#187;

&raquo;

오른쪽 꺾인 괄호

¼

&#188;

&frac14;

4분의 1

½

&#189;

&frac12;

2분의 1

¾

&#190;

&frac34;

4분의 3

¿

&#191;

&iquest;

거꾸로된 물음표

A

&#192;

&Agrave;

Capital A, grave accent

A

&#193;

&Aacute;

Capital A, acute accent

A

&#194;

&Acirc;

Capital A, circumflex accent

A

&#195;

&Atilde;

Capital A, tilde

A

&#196;

&Auml;

Capital A, dieresis or umlaut mark

A

&#197;

&Aring;

Capital A, ring (Angstrom)

Æ

&#198;

&AElig;

Capital AE diphthong (ligature)

C

&#199;

&Ccedil;

Capital C, cedilla

E

&#200;

&Egrave;

Capital E, grave accent

E

&#201;

&Eacute;

Capital E, acute accent

E

&#202;

&Ecirc;

Capital E, circumflex accent

E

&#203;

&Euml;

Capital E, dieresis or umlaut mark

I

&#204;

&Igrave;

Capital I, grave accent

I

&#205;

&Iacute;

Capital I, acute accent

I

&#206;

&Icirc;

Capital I, circumflex accent

I

&#207;

&Iuml;

Capital I, dieresis or umlaut mark

Ð

&#208;

&ETH;

Capital Eth, Icelandic

N

&#209;

&Ntilde;

Capital N, tilde

O

&#210;

&Ograve;

Capital O, grave accent

O

&#211;

&Oacute;

Capital O, acute accent

O

&#212;

&Ocirc;

Capital O, circumflex accent

O

&#213;

&Otilde;

Capital O, tilde

O

&#214;

&Ouml;

Capital O, dieresis or umlaut mark

×

&#215;

&times;

Multiply sign

Ø

&#216;

&Oslash;

width="130"Capital O, slash

U

&#217;

&Ugrave;

Capital U, grave accent

U

&#218;

&Uacute;

Capital U, acute accent

U

&#219;

&Ucirc;

Capital U, circumflex accent

U

&#220;

&Uuml;

Capital U, dieresis or umlaut mark

Y

&#221;

&Yacute;

Capital Y, acute accent

Þ

&#222;

&THORN;

Capital Thorn, Icelandic

ß

&#223;

&szlig;

Small sharp s, German (sz ligature)

a

&#224;

&agrave;

Small a, grave accent

a

&#225;

&aacute;

Small a, acute accent

a

&#226;

&acirc;

Small a, circumflex accent

a

&#227;

&atilde;

Small a, tilde

a

&#228;

&auml;

Small a, dieresis or umlaut mark

a

&#229;

&aring;

Small a, ring

æ

&#230;

&aelig;

Small ae diphthong (ligature)

c

&#231;

&ccedil;

Small c, cedilla

e

&#232;

&egrave;

Small e, grave accent

e

&#233;

&eacute;

Small e, acute accent

e

&#234;

&ecirc;

Small e, circumflex accent

e

&#235;

&euml;

Small e, dieresis or umlaut mark

i

&#236;

&igrave;

Small i, grave accent

i

&#237;

&iacute;

Small i, acute accent

i

&#238;

&icirc;

Small i, circumflex accent

i

&#239;

&iuml;

Small i, dieresis or umlaut mark

ð

&#240;

&eth;

Small eth, Icelandic

n

&#241;

&ntilde;

Small n, tilde

o

&#242;

&ograve;

Small o, grave accent

o

&#243;

&oacute;

Small o, acute accent

o

&#244;

&ocirc;

Small o, circumflex accent

o

&#245;

&otilde;

Small o, tilde

o

&#246;

&ouml;

Small o, dieresis or umlaut mark

÷

&#247;

&divide;

Division sign

ø

&#248;

&oslash;

Small o, slash

u

&#249;

&ugrave;

Small u, grave accent

u

&#250;

&uacute;

Small u, acute accent

u

&#251;

&ucirc;

Small u, circumflex accent

u

&#252;

&uuml;

Small u, dieresis or umlaut mark

y

&#253;

&yacute;

Small y, acute accent

þ

&#254;

&thorn;

Small thorn, Icelandic

y

&#255;

&yuml;

Small y, dieresis or umlaut mark


'프로그래밍 > Web' 카테고리의 다른 글

[jQuery] jQuery를 이용한 팝업. div, layer  (0) 2009.12.16
[json] json 사용법  (0) 2009.12.15
[servlet] servlet  (0) 2009.09.04
[jQuery] jQuery 예제 02  (0) 2009.09.04
[javascript] IE6.0 프레임 - 가로 스크롤바 버그  (0) 2009.08.21

[servlet] servlet

프로그래밍/Web 2009. 9. 4. 14:22 Posted by galad

'프로그래밍 > Web' 카테고리의 다른 글

[json] json 사용법  (0) 2009.12.15
[html] html 특수기호  (3) 2009.09.08
[jQuery] jQuery 예제 02  (0) 2009.09.04
[javascript] IE6.0 프레임 - 가로 스크롤바 버그  (0) 2009.08.21
[ajax] 소스  (0) 2009.08.19

[jQuery] jQuery 예제 02

프로그래밍/Web 2009. 9. 4. 14:22 Posted by galad
출처: http://hyeonseok.com/pmwiki/index.php/Markup/Frame/

인터넷 익스플로러에서 프레임 안에 표준 DTD 문서를 사용할 때 생기는 스크롤바 제거

<!--[if ie]>
<style type="text/css">
html {
overflow: scroll;
overflow-x: auto;
}
</style>
<![endif]-->

[ajax] 소스

프로그래밍/Web 2009. 8. 19. 01:01 Posted by galad
/**
 * BP설명 이미지, BP브랜드 이미지를 삭제한다.(ajax)
 */
function deleteBpFile(fileType) {
    var mbrNo = document.getElementById("mbrNo").value;

    // 이미지 삭제 링크 숨기기
    if(fileType == "BP_DESC") {
        document.getElementById("deleteBpDesc").style.display = "none";
        //document.getElementById("linkBpDesc").style.display = "none";
    }
    else {
        document.getElementById("deleteBpBrand").style.display = "none";
    }

    var parameter = "mbrNo=" + mbrNo + "&fileType=" + fileType;
    //alert(parameter);

    var req = newXMLHttpRequest();
    req.onreadystatechange=getReadyStateXmlHandler(req, fileDeleted);
    req.open("POST", "${pageContext.request.contextPath}/manage/deleteBpFile.omp", true); // 비동기처리여부
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(parameter);
}

/**
 * ajax 응답(xml)을 받아서 처리
 */
function fileDeleted(xml) {
    var bodyTag = xml.getElementsByTagName("body")[0];
    var typeTag = bodyTag.getElementsByTagName("type")[0];
    //alert(typeTag);
    var type = typeTag.firstChild.nodeValue;
    //alert(type);
    var resultTag = bodyTag.getElementsByTagName("result")[0];
    var result = resultTag.firstChild.nodeValue;

    if(result == "Y") {
        // 파일 링크 지우기
        if(type == "BP_DESC") {
            document.getElementById("linkBpDesc").style.display = "none";
        }
        else {
            document.getElementById("linkBpBrand").style.display = "none";
        }
    }
    else {
        // 파일 삭제 링크 다시 보여주기
        if(type == "BP_DESC") {
            document.getElementById("deleteBpDesc").style.display = "";
        }
        else {
            document.getElementById("deleteBpBrand").style.display = "";
        }
    }
}


// ajax call
<span id="linkBpDesc"><strong><s:a href="%{url}"><s:property value="%{umBpInfo.bpDescImgName}"/></s:a></strong></span>
<span id="deleteBpDesc"><a href="#" onclick="deleteBpFile('BP_DESC'); return false;">이미지 삭제</a></span>

Action & Service
// Action
// BP회원 관련 파일 - BP설명이미지, BP브랜드이미지 파일 삭제
    public String deleteBpFile() {
        log.debug("<< ManageAction.deleteBpFile... >>");
       
        HttpServletRequest request = this.getRequest();
       
        String mbrNo = request.getParameter("mbrNo");
        String fileType = request.getParameter("fileType");
       
        log.debug("mbrNo = " + mbrNo);
        log.debug("fileType = " + fileType);
       
        String xml = this.manageService.deleteBpFile(mbrNo, fileType);
        setInputStream(new ByteArrayInputStream(xml.getBytes()));
       
        return SUCCESS;
    }

// 설정파일
<!-- 파일 삭제 -->
        <action name="deleteBpFile" class="com.omp.bp.cms.manage.action.ManageAction" method="deleteBpFile">
            <result type="stream">
                <param name="inputName">inputStream</param>
                <param name="contentType">text/xml</param>
                <param name="bufferSize">4096</param>
            </result>
        </action>

// Service
// BP추가 파일 삭제 후, 결과를 XML형식으로 반환
    @SuppressWarnings("unchecked")
    public String deleteBpFile(String mbrNo, String fileType) throws ServiceException {
        log.debug("<ManageServiceImpl> deleteBpFile...");
       
        StringBuffer xml = null;
        UserMemberBpInfo umbi = null;
       
        try {
            // DB에서 파일 경로를 얻음
            umbi = this.manageDAO.getMemberBpinfo(mbrNo);
            if(umbi == null) {
                throw new ServiceException("BP추가 파일 삭제 중 BP회원 정보 읽기 실패", "getMemberBpinfo FAIL");
            }
           
            // 파일경로 변경 - 앞에 /data 붙이기
            umbi = DataUtil.makeFilePathFromDB(umbi);
           
            // fileType에 따라 파일 삭제
            if(StringUtils.equalsIgnoreCase(fileType, "BP_DESC")) {
                File f = new File(umbi.getBpDescImgPath());
                if(f.exists() && f.isFile()) {
                    if(!f.delete()) {
                        throw new ServiceException("BP추가 파일 삭제 중 설명 파일 삭제 실패", "delete FAIL");
                    }
                    else {
                        log.debug("BP 설명 물리 파일 삭제");
                       
                        // DB 갱신 - 파일 경로 삭제
                        Map map = new HashMap();
                        map.put("mbrNo", mbrNo);
                        map.put("fileType", fileType);
                        if(!this.manageDAO.deleteBpFile(map)) {
                            throw new ServiceException("BP추가 파일 삭제 중 DB 갱신 실패", "update db FAIL");
                        }
                       
                        log.debug("BP 설명 파일 경로 삭제");
                    }
                }
            }
            else if(StringUtils.equalsIgnoreCase(fileType, "BP_BRAND")) {
                File f = new File(umbi.getBpTbnailImgPath());
                if(f.exists() && f.isFile()) {
                    if(!f.delete()) {
                        throw new ServiceException("BP추가 파일 삭제 중 브랜드 파일 삭제 실패", "delete FAIL");
                    }
                    else {
                        log.debug("BP 브랜드 물리 파일 삭제");
                       
                        // DB 갱신 - 파일 경로 삭제
                        Map map = new HashMap();
                        map.put("mbrNo", mbrNo);
                        map.put("fileType", fileType);
                        if(!this.manageDAO.deleteBpFile(map)) {
                            throw new ServiceException("BP추가 파일 삭제 중 DB 갱신 실패", "update db FAIL");
                        }
                       
                        log.debug("BP 브랜드 파일 경로 삭제");
                       
                    }
                }
            }
           
            // 삭제 결과를 XML로 작성
            xml = makeXmlForDeleteBpFileResult(fileType, true);
        }
        catch(Exception e) {
            log.debug("BP추가 파일 삭제 실패", e);
            xml = makeXmlForDeleteBpFileResult(fileType, false);
        }
       
        return xml.toString();
    }
   
    private StringBuffer makeXmlForDeleteBpFileResult(String fileType, boolean isSucceeded) {
        StringBuffer xml = new StringBuffer();
       
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xml.append("<body>");
            xml.append("<type>");
            xml.append(fileType);
            xml.append("</type>");
            xml.append("<result>");
            xml.append(isSucceeded ? "Y" : "N");
            xml.append("</result>");
        xml.append("</body>");
       
        log.debug("DELETE BP FILE - XML");
        log.debug(xml.toString());
       
        return xml;
    }

의외로 간단하기도 하지만 스크립트쪽 처리가 복잡할 듯.
gmail, google docs 같은 건 정말 어떻게 만든 건지 신기할 뿐..
!!! IE 6.0밖에 안되는 듯?!!!!
아마도 FF문제와 같이 locally loaded image에 대해서는 IE6.0밖에 안되는 듯

내가 사용하는 버젼

문제: callback 함수에는 인자 넘기기가 불가능한가?
전역변수로 해결하였으나 다른 방법은 없는가??

참고: http://www.coderanch.com/t/121417/HTML-JavaScript/Passing-Parameter-Into-Callback-Function

jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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="image_util.js"></script>

<script type="text/javascript">
function fileCheck(formObj) {
    if(formObj.fileName.value == "") {
        alert("이미지를 선택해주세요.");
        return false;
    }
    if(formObj.checkUploadImgOkYn.value != "Y") {
        alert("업로드 할 수 없는 이미지 파일입니다.");
        return false;
    }

    return true;
}
</script>
</head>
<body>
<form name="F" onsubmit="return fileCheck(this);">
<input type="file" name="fileName" onChange="checkUploadImg(this.value, 'checkUploadImgOkYn', 'jpg' ,1600, 1200, 500)" >
<input type="hidden" name="checkUploadImgOkYn" id="checkUploadImgOkYn" value="N">
<br>
<input type="submit">
</form>
</body>
</html>

js
// 이미지 파일 관련 javascript

/**
 * 파일 확장자를 반환
 * @param filePath 파일 path
 * @return 확장자
 */
function getFileExtension(filePath)
{
    var lastIndex = -1;
    lastIndex = filePath.lastIndexOf('.');
    var extension = "";

    if ( lastIndex != -1 )
    {
        //extension = filePath.substring( lastIndex+1, filePath.len );
        extension = filePath.substring( lastIndex+1);
    } else {
        extension = "";
    }
   
    return extension;
}


// 이미지.onload시의 callback 함수에 파라미터를 넘기기 위한 전역변수
var g_objId = "";            // 이미지 체크 후, 그 결과를 설정할 input태그의 id. ex) <input type="hidden" name="checkUploadImgOkYn" id="checkUploadImgOkYn" value="N">
var g_widthLimit = 0;    // 이미지 최대 가로길이
var g_heightLimit = 0;    // 이미지 최대 세로길이
var g_fileSizeLimit = 0;    // 이미지 최대 파일크기

/**
 * 이미지 업로드 태그에서 부를 함수. ex) &lt;input type="file" name="fileName" onChange="checkUploadImg(this.value, 'checkUploadImgOkYn', 'jpg' ,1600, 1200, 500)" >
 * @param imgSrc 이미지 파일
 * @param objId 이미지 체크 후 결과를 설정할 input태그의 id
 * @param fileExt_limit 이미지 파일 확장자 제한
 * @param width_limit 이미지 최대 가로길이
 * @param height_limit 이미지 최대 세로길이
 * @param fileSize_limit 이미지 최대 파일크기
 * @return 없음. 체크에 성공하면 objId에 Y를 설정. 실패하면 N을 설정함.
 */
function checkUploadImg(imgSrc, objId, fileExt_limit, width_limit, height_limit, fileSize_limit)
{
    var widthLimit = 0;
    var heightLimit = 0;
    var fileSizeLimit = 0;
    var fileExtLimit = "";
   
    if(typeof width_limit != "undefined") { // 제약조건이 있으면
        widthLimit = width_limit;
    }
    if(typeof height_limit != "undefined") { // 제약조건이 있으면
        heightLimit = height_limit;
    }
    if(typeof fileSize_limit != "undefined") { // 제약조건이 있으면
        fileSizeLimit = fileSize_limit;
    }
    if(typeof fileExt_limit != "undefined") { // 제약조건이 있으면
        fileExtLimit = fileExt_limit;
    }
    else { // 이미지 파일만 업로드해야 하므로 조건이 없으면 기본설정
        fileExtLimit = "jpg,gif,png";
    }

    // global 변수에 저장. callback함수에 인자 넘기기 불가하기 때문
    g_objId = objId;
    g_widthLimit = widthLimit;
    g_heightLimit = heightLimit;
    g_fileSizeLimit = fileSizeLimit;
   
    // IE 체크
    if(navigator.userAgent.toLowerCase().indexOf("msie") == -1) { // IE가 아니면
        var msg = "파일 확장자 : " + fileExtLimit;
        msg = (widthLimit != 0) ? msg + " , 이미지 가로 길이 : " + widthLimit : msg;
        msg = (heightLimit != 0) ? msg + " , 이미지 가로 길이 : " + heightLimit : msg;
        msg = (fileSizeLimit != 0) ? msg + " , 이미지 가로 길이 : " + fileSizeLimit : msg;
       
        alert("인터넷 익스플로러가 아닌 경우에는 업로드할 그림을 확인할 수 없습니다.\n다음의 조건에 맞는 파일을 업로드해 주세요.\n" + msg);
        document.getElementById(g_objId).value = "Y";
        return;
    }
   
    if(typeof imgSrc == "undefined" || imgSrc == "") {
        alert("선택된 파일이 없습니다.");
    }

    var ext = getFileExtension(imgSrc);
    //alert(ext);

    if (ext == "") {
        alert('올바른 파일을 입력하세요');
        return;
    }
    else if(fileExtLimit != "" && ext.toLowerCase().indexOf(fileExtLimit.toLowerCase()) == -1) { // 제약조건이 없으면 체크 안 함
        alert(fileExtLimit + " 형식의 파일만 가능합니다.");
        return;
    }
   
    LoadImg(imgSrc);
}

/**
 * 이미지를 로드
 * @param imgSrc 이미지 파일 path
 * @return
 */
function LoadImg(imgSrc)
{
    var imgInfo = new Image();
    imgInfo.onload = img_Loaded;
    imgInfo.onerror = function() {
        // always called
        alert("이미지 파일의 로드에 실패했습니다.");
        document.getElementById(g_objId).value = "N";
    };
    imgInfo.src = imgSrc;
}

/**
 * image.onload의 callback 함수. image가 load 되면 불려진다.
 * @return
 */
function img_Loaded()
{
    /*var imgSrc, imgWidth, imgHeight, imgFileSize;
    imgSrc = this.src;
    imgWidth = this.width;
    imgHeight = this.height;
    imgFileSize = this.fileSize;

    alert(imgWidth);*/

    var objId = g_objId;
    var widthLimit = g_widthLimit;
    var heightLimit = g_heightLimit;
    var fileSizeLimit = g_fileSizeLimit;
    //alert(widthLimit);
    //alert(heightLimit);
   
    if (this.src == "" || this.width <= 0 || this.height <= 0)
    {
        alert("이미지 파일의 로드에 실패했습니다.");
        document.getElementById(objId).value = "N";
        return;
    }

    // 제약조건 확인
    if(widthLimit != 0 && this.width > widthLimit) {
        alert("선택한 이미지의 가로 길이가 허용치인 " + widthLimit + " 를 초과했습니다.\n선택한 이미지의 가로 길이는 " + this.width + " 입니다.");
          document.getElementById(objId).value = "N";
        return;
    }
    if(heightLimit != 0 && this.height > heightLimit) {
        alert("선택한 이미지의 세로 길이가 허용치인 " + heightLimit + " 를 초과했습니다.\n선택한 이미지의 세로 길이는 " + this.height + " 입니다.");
          document.getElementById(objId).value = "N";
        return;
    }
    if(fileSizeLimit != 0 && this.fileSize > fileSizeLimit*1024) {
        alert("선택한 이미지 크기가 허용치인 " + fileSizeLimit + "KB 를 초과했습니다.\n선택한 이미지의 크기는 약 " + Math.ceil(this.fileSize/1024) + "KB 입니다.");
          document.getElementById(objId).value = "N";
        return;
    }

    // 제약조건 이내라면
    document.getElementById(objId).value = "Y";

    //이미지 사이즈 저장
    //document.F.imgWidth.value = imgWidth;
    //document.F.imgHeight.value = imgHeight;

    //alert("this.width = " + this.width);
    //alert("this.height = " + this.height);

    //alert(document.getElementById(objId).value);
}


!!! IE 6.0밖에 안되는 듯?!!!!
아마도 아래의 FF문제와 같이 locally loaded image에 대해서는 IE6.0밖에 안되는 듯

일단 firefox에서는 image.onload가 업로드 하려는 파일, 즉 locally loaded image에 대해서는 작동하지 않는다
(참고: http://www.tek-tips.com/viewthread.cfm?qid=1452885&page=5)

대신에 image.src="http://www.tek-tips.com/images/logo.gif" 와 같이 어딘가의 서버상에 올려져 있는 파일에 대해서는 작동한다.

 function LoadImg(value)
{
    var imgInfo = new Image();
    imgInfo.onload = img_Load;
    imgInfo.onerror = function() {
        // always called
        alert('error');
    };
// imgInfo.src = "http://www.tek-tips.com/images/logo.gif"; // 이렇게 하면 firefox에서도 동작함
    imgInfo.src = value;
}

function img_Load()
{
    var imgSrc, imgWidth, imgHeight, imgFileSize;
    var maxFileSize;
    maxFileSize = 5000000;
    imgSrc = this.src;
    imgWidth = this.width;
    imgHeight = this.height;
    imgFileSize = this.fileSize;

    if (imgSrc == "" || imgWidth <= 0 || imgHeight <= 0)
    {
        alert('그림파일을 가져올 수 없습니다.');
        return;
    }

    if (imgFileSize > maxFileSize)
    {
        alert('선택하신 그림 파일은 허용 최대크기인 ' + maxFileSize/1024 + ' KB 를 초과하였습니다.');
        return;
    }

    //이미지 사이즈 저장
    document.F.imgWidth.value = imgWidth;
    document.F.imgHeight.value = imgHeight;

    alert(imgWidth);
    alert(imgHeight);
}

주의할 건 image.onload 이후에 image.src 가 와야한다는 것.
image.src 에서 실제 이미지를 로드하고 나서, onload가 동작하는 원리인 듯.
src가 먼저오면 onload가 되기도 하고 아니기도 하는 듯.

기타 참고 링크
http://dogfeet.tistory.com/20
http://www.juniac.net/183
http://blog.byuli.com/entry/운영체제와-브라우저-체크
참고: http://x1210.tistory.com/385
http://htmlcleaner.sourceforge.net/index.php

public String getResultCode(String resp) throws IOException {
        // create an instance of HtmlCleaner
        HtmlCleaner cleaner = new HtmlCleaner();

        // take default cleaner properties
        CleanerProperties props = cleaner.getProperties();
         
//        // customize cleaner's behaviour with property setters
//        props.setXXX(...);
       
        // Clean HTML taken from simple string, file, URL, input stream,
        // input source or reader. Result is root node of created
        // tree-like structure. Single cleaner instance may be safely used
        // multiple times.
        TagNode node = cleaner.clean(resp);

        // optionally find parts of the DOM or modify some nodes
//        TagNode[] myNodes = node.getElementsByName(MLBConstants.MCODE_RESULT_NAME, true);
        TagNode[] myNodes = node.getElementsByName("input", true);
//        // and/or
//        Object[] myNodes = node.evaluateXPath(xPathExpression);
//        // and/or
//        aNode.removeFromTree();
//        // and/or
//        aNode.addAttribute(attName, attValue);
//        // and/or
//        aNode.removeAttribute(attName, attValue);
//        // and/or
//        cleaner.setInnerHtml(aNode, htmlContent);
         
//        // serialize a node to a file, output stream, DOM, JDom...
//        new XXXSerializer(props).writeXmlXXX(aNode, ...);
//        myJDom = new JDomSerializer(props, true).createJDom(aNode);
//        myDom = new DomSerializer(props, true).createDOM(aNode);
       
        String resultCode = "";
       
        for(int i = 0; i < myNodes.length; i++) {
           
            System.out.println("name = " + myNodes[i].getAttributeByName("name"));
           
            if(myNodes[i].getAttributeByName("name").equals("result")) {
                resultCode = myNodes[i].getAttributeByName(MLBConstants.MCODE_RESULT_ATTRIBUTE);
                System.out.println(">>> value of result = " + resultCode);
            }
        }
       
        return MLBConstants.getMcodeRequestResultMessage(resultCode);
    }


html
                            <td nowrap style="width:225px;margin-bottom:1px;">
                                <s:select name="approvalStage" list="stageCodeList" listKey="key" listValue="value" headerKey="" headerValue="--선택(현재 상태)--" onchange="selectStageCode(this);"></s:select>
                            </td>
                            <td nowrap style="width:85px;margin-bottom:1px;" id="dpStageTd">
                                <div id="dpStage" style="display: none;"><img src="../images/button/btn_next.gif" align="middle"> 상용상태</div>
                            </td>
                            <td nowrap style="width:225px;margin-bottom:1px;">
                                <div id="dpStageSelect" style="display: none;"><s:select name="dpStageSelect" list="dpStageCodeList" listKey="key" listValue="value" headerKey="" headerValue="전체"></s:select></div>
                            </td>
                            <td align="right" nowrap style="margin-bottom:1px;">
                                <img id="searchButton" src="../images/button/btn_search.gif" align="middle" onClick="javascript:searchContent();" style="cursor:hand;">
                            </td>


script
    function selectStageCode(obj) {
        var STAGE_CODE_RELEASED = "<%=WorkflowCodeDef.STAGE_CODE_RELEASED%>";
       
        //alert(obj.value);
        if(obj.value == STAGE_CODE_RELEASED) { // 상용이면
            document.getElementById("dpStageTd").setAttribute("className", "subject");
            document.getElementById("dpStage").style.display="";
            document.getElementById("dpStageSelect").style.display="";
        }
        else {
            document.getElementById("dpStageTd").setAttribute("className", "");
            document.getElementById("dpStage").style.display="none";
            document.getElementById("dpStageSelect").style.display="none";
        }
    }



[jQuery] jQuery 예제 01

프로그래밍/Web 2009. 7. 17. 16:49 Posted by galad
출처: http://www.jiny.kr/jiny/417
위의 출처의 예제를 직접 해보면서 작성한 소스를 붙여넣고, 몇몇 사항들은 삭제/추가하였음...
문제있으면 알려주시길...

http://hanjiq.egloos.com/2108204
http://orangenius.tistory.com/5
http://jqueryui.com/home


size( ) 
Returns: Number
size( ), 실행후 숫자를 반환

The number of elements in the jQuery object.
매치되어진 원소들의 갯수를 반환한다.
<!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=EUC-KR">
<title>01</title>

<style>
body { cursor:pointer; }
div { width:50px; height:30px; margin:5px; float:left; background:blue; }
span { color:red; }
</style>
 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $(document.body).click(function() {
        $(document.body).append($("<div>"));
        var n = $("div").size();
        //var n = $("div").length; // size()와 같다
        $("span").text("There are " + n + " divs. Click to add more.");
    }).click(); // 한 번 강제로 클릭 - 아래의 body에는 div가 3개인데 실행되면서 4개로 화면에 표시된다.
});
</script>

</head>
<body>

<span></span>
<div></div>
<div></div>
<div></div>

</body>
</html>
/JQueryTest01/WebContent/Example01/01.html

get( ) 
Returns: Array<Element>
get( ), 실행후 원소 배열 반환

Access all matched DOM elements.
매치되는 모든 문서 원소들을 배열로 반환한다
<!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=EUC-KR">
<title>02</title>

<style>
span { color:red; }
</style>
 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    disp($("div").get().reverse()); // get으로 array를 얻어서, reverse로 순서뒤집기
});

function disp(divs) {
    var a = [];
    for(var i = 0; i < divs.length; i++) {
        a.push(divs[i].innerHTML);
    }

    $("span").text(a.join(" "));
}
</script>

</head>
<body>

Reversed - <span></span>
<div>One</div>
<div>Two</div>
<div>2.5</div>
<div>Three</div>

</body>
</html>
/JQueryTest01/WebContent/Example01/02.html

get( index ) 
Returns: Element
get( 인덱스 ), 실행후 매치 되는 원소를 반환

Access a single matched DOM element at a specified index in the matched set.
매치되는 원소들 중 주어진 인덱스에 해당하는 하나의 원소만 반환한다.

<!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=EUC-KR">
<title>02</title>

<style>
span { color:red; }
div { background:yellow; }
</style>
 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("*", document.body).click(function (e) {
        e.stopPropagation(); // 이벤트 정지
        var domEl = $(this).get(0); // 클릭한 객체를 받음
        $("span:first").text("Clicked on - " + domEl.tagName); // 태그명 표시
    });
});
</script>

</head>
<body>

<span> </span>
<p>In this paragraph is an <span>important</span> section</p>
<div><input type="text" /></div>

</body>
</html>

event.stopPropagation

https://developer.mozilla.org/en/DOM:event.stopPropagation
jQuery함수가 아니라 DOM 객체 함수임.

Prevents further propagation of the current event.
현재 이벤트가 더 진행하는 것을 방지
<html>
<head>
<title>Event Propagation</title>

<style type="text/css">
 #t-daddy { border: 1px solid red }
 #c1 { background-color: pink; }
</style>

<script type="text/javascript">

function stopEvent(ev) {
  c2 = document.getElementById("c2");
  c2.innerHTML = "hello";

  // this ought to keep t-daddy from getting the click.
  ev.stopPropagation();
  alert("event propagation halted.");
}

function load() {
  elem = document.getElementById("tbl1");
  elem.addEventListener("click", stopEvent, false);
}
</script>
</head>

<body onload="load();">

<table id="t-daddy" onclick="alert('hi');">
 <tr id="tbl1">
  <td id="c1">one</td>
 </tr>
 <tr>
  <td id="c2">two</td>
 </tr>
</table>

</body>
</html>
/JQueryTest01/WebContent/Example01/03.html

출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using the tablesorter plugin
http://tablesorter.com/docs/
$("#myTable").tablesorter();
---------------------------------------------
<table id="myTable">
<thead>
<tr>
    <th>Last Name</th>
    <th>First Name</th>
    <th>Email</th>
    <th>Due</th>
    <th>Web Site</th>
</tr>
</thead>
<tbody>
<tr>
    <td>Smith</td>
    <td>John</td>
    <td>jsmith@gmail.com</td>
    <td>$50.00</td>
    <td>http://www.jsmith.com</td>
</tr>
<tr>
    <td>Bach</td>
    <td>Frank</td>
    <td>fbach@yahoo.com</td>
    <td>$50.00</td>
    <td>http://www.frank.com</td>
</tr>
<tr>
    <td>Doe</td>
    <td>Jason</td>
    <td>jdoe@hotmail.com</td>
    <td>$100.00</td>
    <td>http://www.jdoe.com</td>
</tr>
<tr>
    <td>Conway</td>
    <td>Tim</td>
    <td>tconway@earthlink.net</td>
    <td>$50.00</td>
    <td>http://www.timconway.com</td>
</tr>
</tbody>
</table>
<thread> 태그 안에 있는 것을 클릭하면 테이블을 정렬한다. 신기하네...
숫자, 문자 등을 알아서 판별한다고 하는군. 상세한 것은 위의 링크를 참조.

$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
This tells tablesorter to sort on the first and second column in ascending order.
정렬 초기값 설정.

Sort multiple columns simultaneously by holding down the shift key and clicking a second, third or even fourth column header!
하나 선택해서 그걸 기준으로 정렬하고 쉬프트 클릭하고 다른 것 선택하면 계단식으로 정렬됨(기존 정렬을 기준으로 다시 정렬).

속도만 받쳐주면 테이블 정렬은 이걸로 해도 될듯?!
출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using Effects
$(document).ready(function(){
   $("a").toggle(function(){
     $(".stuff").hide('slow');
   },function(){
     $(".stuff").show('fast');
   });
 });
소스 버전이 옛날 것인가... 제대로 동작하질 않는군..

http://docs.jquery.com/Effects/toggle
위의 링크된 문서를 참고할 것

$(document).ready(function() {
    $("#btn1").click(function() {
        $("p").toggle();
        $("#hbtn").toggle();
    });
});

-----------------------------------------

<button id="btn1">Toggle</button>
<p class="tg">Hello</p>
<p class="tg" style="display: none;">Toggle!</p>
<p>AAA</p>
<p style="display: none;">BBB</p>
<button id="hbtn" style="display: none;">hidden button</button>
해보면 toggle()한 display:none이 아닌 것은 안보이게 되고, display:none이었던 것은 보이게된다.

var flip = 0;
$("button").click(function () {
    $("p").toggle( flip++ % 2 == 0 );
});
toggle(XXX)안에 식을 넣는 것도 가능. true면 보이고, false면 숨긴다.

$("button").click(function () {
    $("p").toggle("slow");
});
toggle("slow"). 천천히 사라지고 천천히 나타남.
slow, fast, normal 이 있고, 직접 밀리세컨드로 속도를 지정할 수 있다.

$("button").click(function () {
    $("p").toggle("slow", doCallback);
});

function doCallback() {
    // do something
    this; // DOM element
}
이런 식으로 토글 이펙트가 끝났을 때 실행될 callback 함수도 지정 가능.
여러 개가 토글 되는 경우 각각 실행됨.
사라지는 토글이라고 해서 사라지는 DOM의 callback만 실행되는 것이 아니라, 나타나는 DOM의 callback도 실행된다.
즉 어찌됐든 토글되는 모든 DOM의 callback이 실행됨.

기타 Effects는 아래 링크를 참조.
http://docs.jquery.com/Effects

Animate
// Using multiple unit types within one animation.
$("#go").click(function(){
    $("#block").animate({
        width: "70%",
        opacity: 0.4,
        marginLeft: "0.6in",
        fontSize: "3em",
        borderWidth: "10px"
    }, 1500 );
});
---------------------------------------------------
<button id="go">» Run</button>
<div id="block">Hello!</div>
#block이 초기 모양에서 animate({XXX}, YYY)에 설정된 모양(XXX)으로 변형된다. 이 때, YYY는 변형 시간(클 수록 천천히).

$("#go1").click(function(){
    $("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } )
         .animate( { fontSize:"24px" }, 1500 )
         .animate( { borderRightWidth:"15px" }, 1500
    );
});

$("#go2").click(function(){
    $("#block2").animate( { width:"90%"}, 1000 )
         .animate( { fontSize:"24px" } , 1000 )
         .animate( { borderLeftWidth:"15px" }, 1000
    );
});

$("#go3").click(function(){
    $("#go1").add("#go2").click();
});

$("#go4").click(function(){
    $("div").css({width:"", fontSize:"", borderWidth:""});
});
---------------------------------------------------
<button id="go1">» Animate Block1</button>
<button id="go2">» Animate Block2</button>
<button id="go3">» Animate Both</button>
<button id="go4">» Reset</button>
<div id="block1">Block1</div>
<div id="block2">Block2</div>
$("#ID").animate({AAA},AAA).animate({BBB},BBB).animate({CCC},CCC); AAA, BBB, CCC의 순서대로 애니메이트됨.
queue:false 옵션이 있으면 순서 상관없이 동시에 애니메이트됨.

$("#go1").add("#go2").click(); go1과 go2를 동시에 클릭 이벤트 발생시킴.


animate()
Arguments:
paramsOptions
A set of style attributes that you wish to animate, and to what end.
duration (Optional)String, Number
A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
easing (Optional)String
The name of the easing effect that you want to use (plugin required). There are two built-in values, "linear" and "swing".
callback (Optional)Function
A function to be executed whenever the animation completes, executes once for each element animated against.

$("p").animate({
      "height": "toggle", "opacity": "toggle"
}, { duration: "slow" });
Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
라는데, height랑 opacity를 토글하는게 무슨 효과인지 모르겠다.

나머진 위의 링크 참조...


'프로그래밍 > Web' 카테고리의 다른 글

[jQuery] jQuery 예제 01  (0) 2009.07.17
[jQuery] Getting Started with jQuery 04  (0) 2009.07.11
[jQuery] Getting Started with jQuery 02  (0) 2009.07.10
[jQuery] Getting Started with jQuery 01  (0) 2009.07.10
[jQuery] How jQuery Works  (0) 2009.07.06
출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using Ajax
<!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=ISO-8859-1" />
<title>jQuery Starterkit</title>

<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    // generate markup
    var ratingMarkup = ["Please rate: "];
    for(var i=1; i <= 5; i++) {
        ratingMarkup[ratingMarkup.length] = "<a href='#'>" + i + "</a> ";
    }
    var container = $("#rating");
    // add markup to container
    container.html(ratingMarkup.join(''));
   
    // add click handlers
    container.find("a").click(function(e) {
        e.preventDefault();
        // send requests
        $.post("starterkit/rate.php", {rating: $(this).html()}, function(xml) {
            // format result
            var result = [
                "Thanks for rating, current average: ",
                $("average", xml).text(),
                ", number of votes: ",
                $("count", xml).text()
            ];
            // output result
            $("#rating").html(result.join(''));
        } );
    });
});
</script>

</head>
<body>
<h1>jQuery Getting Started Example - rate me</h1>
<p>This example demonstrate basic use of AJAX. Click one of the links below to rate. The
number of rating and the average rating will be returned from the serverside script and displayed.</p>

<div id="rating">Container</div>

</body>
</html>
$("average", xml).text() -> 결과로 받은 xml에서 <average>XXX</average>를 찾아서 text 값을 가져온다.
딱히 구조(부모-자식)는 상관없는 듯.

기타 참고 사항.
ajax 사용 시 주의점

A very common problem encountered when loading content by Ajax is this: When adding event handlers to your document that should also apply to the loaded content, you have to apply these handlers after the content is loaded. To prevent code duplication, you can delegate to a function.
Example:
function addClickHandlers() {
   $("a.remote", this).click(function() {
     $("#target").load(this.href, addClickHandlers);
   });
 }
 $(document).ready(addClickHandlers);

Now addClickHandlers is called once when the DOM is ready and then everytime when a user clicked a link with the class remote and the content has finished loading.

Note the $("a.remote", this) query, this is passed as a context: For the document ready event, this refers to the document, and it therefore searches the entire document for anchors with class remote. When addClickHandlers is used as a callback for load(), this refers to a different element: In the example, the element with id target. This prevents that the click event is applied again and again to the same links, causing a crash eventually.

Another common problem with callbacks are parameters. You have specified your callback but need to pass an extra parameter. The easiest way to achieve this is to wrap the callback inside another function:
// get some data
 var foobar = ...;
 
 // specify handler, it needs data as a paramter
 function handler(data) {
   //...
 }
 
 // add click handler and pass foobar!
 $('a').click(function(){
   handler(foobar);
 });
 
 // if you need the context of the original handler, use apply:
 $('a').click(function(){
   handler.apply(this, [foobar]);
 });


출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

간단한 부분은 제외.

Using selectors and events

$(document).ready(function() {
   $("#orderedlist").addClass("red");
 });
id가 orderedlist 인 것을 찾아서 red 클래스를 추가

$(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
 });
orderedlist 가 갖는 모든 li 태그에 blue 클래스 추가

$(document).ready(function() {
   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green");
   });
 });
orderedlist 가 갖는 마지막 li 태그 위에 커서가 오면 green 클래스를 추가하고, 커서가 나가면 green 클래스를 제거

$(document).ready(function() {
   $("#orderedlist").find("li").each(function(i) {
     $(this).append( " BAM! " + i );
   });
 });
orderedlist 의 li 태그들을 찾아서, 각각의 li 태그 내의 값(<li>XXX</li>)에 BAM! 현재 카운트를 붙인다.
each(function(i) {...}) 에서 i 가 루프의 현재 카운트 값. 시작은 0.

$(document).ready(function() {
   // use this to reset a single form
   $("#reset").click(function() {
     $("form")[0].reset();
   });
 });

$(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });
폼 리셋하기.
위는 폼이 1개일 때. 밑은 여러 개일 때.

$(document).ready(function() {
   $("li").not(":has(ul)").css("border", "1px solid black");
 });
ul 태그를 갖지 않는 모든 li 태그에 주어진 css 스타일을 적용(border를 1px solid black으로).
원래는 모든 li 태그를 찾고 그 중에서, ul 태그를 갖는 li 태그를 제거.

$(document).ready(function() {
   $("a[name]").css("background", "#eee" );
 });
XPath 형식의 객체 선택.
name 속성을 갖는 a 태그를 선택해서 css 스타일 적용.