//==================================================================

// 스크립트 오류 메세지

//==================================================================

function myDebug(errmsg, url, linenum)

{

    errWin=window.open('','','width=350,height=220,scrollbars=no');

    errWin.document.open();

    errWin.document.write('<CENTER><H1>스크립트오류 정보</H2></CENTER>');

    errWin.document.write('에러메시지: <FONT COLOR=RED>'+errmsg+'</FONT><BR>');

    errWin.document.write('에러가 난 문서: <FONT COLOR=RED>'+url+'</FONT><BR>');

    errWin.document.write('에러가 난 라인: <FONT COLOR=RED>'+linenum+'</FONT>');

    errWin.document.close();


    return true;

}

window.onerror=myDebug;


posted by 뚱2

[JSON] JSON

JavaScript/Json 2012. 10. 30. 11:11

출처 : http://www.json.org/json-ko.html 


JSON (JavaScript Object Notation)은 경량의 DATA-교환 형식이다. 이 형식은 사람이 읽고 쓰기에 용이하며, 기계가 분석하고 생성함에도 용이하다.JavaScript Programming LanguageStandard ECMA-262 3rd Edition - December 1999의 일부에 토대를 두고 있다. JSON은 완벽하게 언어로 부터 독립적이지만 C-family 언어 - C, C++, C#, Java, JavaScript, Perl, Python 그외 다수 - 의 프로그래머들에게 친숙한 관습을 사용하는 텍스트 형식이다. 이러한 속성들이 JSON을 이상적인 DATA-교환 언어로 만들고 있다.

JSON은 두개의 구조를 기본으로 두고 있다:

  • name/value 형태의 쌍으로 collection 타입. 다양한 언어들에서, 이는 object, record, struct(구조체), dictionary, hash table, 키가 있는 list, 또는 연상배열로서 실현 되었다.
  • 값들의 순서화된 리스트. 대부분의 언어들에서, 이는 array, vector, list, 또는 sequence로서 실현 되었다.

이러한 것들은 보편적인 DATA 구조이다. 사실상 모든 현대의 프로그래밍 언어들은 어떠한 형태로든 이것들을 지원한다. 프로그래밍 언어들을 이용하여 호환성 있는 DATA 형식이 이러한 구조들을 근간에 두고 있는 것은 당연하다.

JSON 에서, 이러한 형식들을 가져간다:

object는 name/value 쌍들의 비순서화된 SET이다. object는 { (좌 중괄호)로 시작하고 } (우 중괄호)로 끝내어 표현한다. 각 name 뒤에 : (colon)을 붙이고, (comma)로 name/value 쌍들 간을 구분한다.

array은 값들의 순서화된 collection 이다. array는 [ (left bracket)로 시작해서 ] (right bracket)로 끝내어 표현한다. , (comma)로 array의 값들을 구분한다.

value는 큰따옴표안에 stringnumber ,true ,false , nullobject ,array이 올수 있다. 이러한 구조들을 포함한다.

string은 큰따옴표안에 둘러 싸인 zero 이상 Unicode 문자들의 조합이며, 쌍다옴표안에 감싸지며,backslash escape가 적용된다. 하나의 문자(character)도 하나의 문자열(character string)로서 표현된다. string은 C 또는 Java 문자열 처럼 매우 많이 비슷하다.

number는 8진수와 16진수 형식을 사용하지 않는것을 제외하면 C와 Java number 처럼 매우 많이 비슷하다.

토근들의 어떤 쌍 사이에 공백을 삽입할수 있다. 드물게 encode된 세부 항목을 제외하면, 이렇게 설명된 JSON의 형식은 완벽하게 그 언어를 설명한다.


posted by 뚱2

[html] Zen Coding 링크

JavaScript/Html 2012. 9. 23. 16:23



링크 : http://code.google.com/p/zen-coding/ 

이클립스용 젠코딩 : http://zziuni.pe.kr/zziuni/551

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

[html] dd, dt, dl  (0) 2012.06.22
[html] http 프로토콜  (0) 2012.02.16
[html] html 특수문자 태그  (0) 2011.08.18
[html] map 사용  (0) 2011.07.22
posted by 뚱2

var str = "10,000";

if ( /\b(?:\d{1,3})(?:,\d{3})*(?:\.\d+)?\b/.test(str) == true ) {

    alert("천단위 수");

}

else {

    alert("천단위 수가 아닙니다.");

}


posted by 뚱2

http://easymicro.egloos.com/5488188 

http://blog.naver.com/PostView.nhn?blogId=rookieangel&logNo=140155967057  


http://www.superkts.pe.kr/helper/view.php?seq=264&PHPSESSID=5447acbb880ada74d8d967e36eac58eb 




posted by 뚱2

var str = "한글 입니다. test";

if ( /.*?[가-힣]+.*?/.test(str) == true ) {

alert("한글이 존재합니다.");

}

else {

alert("한글이 존재하지 않습니다.");

}


posted by 뚱2

;(function(exports, $) {

/**

* 전달받은 인자를 부모로 하는 새로운 객체를 생성한다.

*/

if ( typeof Object.create !== 'function' ) {

Object.create = function(o) {

var F = function() {};

if ( !arguments.length ) {

F.prototype = o;

}

return new F();

};

}

/**

* 객체에 메소드를 추가하는 메소드

* @param name

* @param code

*/

Function.prototype.method = function(name, code) {

if ( !this.prototype[name] ) {

this.prototype[name] = code;

}

};

/**

* 함수설명 : " abcde "  -> "abcde" 공백제거

* 예제     : str.trim();

*/

String.method("trim", function(){

   return this.replace(/(^\s*)|(\s*$)/g, "");

}); 

/**

* 함수설명 : " ab c de "  -> "abcde" 모든 공백제거

* 예제     : str.allTrim()

*/

String.method("allTrim", function(){

   return this.replace(/\s*/g, "");

});


/**

* 함수설명 : " abcd" -> "abcd"

* 왼쪽 공백 제거

*/

String.method("leftTrim", function() {

return this.replace(/(^\s*)/g, "");

});


/**

* 함수설명 : "abcd " -> "abcd"

* 오른쪽 공백 제거

*/

String.method("rightTrim", function() {

return this.replace(/(\s*$)/g, "");

});


/**

*함수설명 : cut 메소드를 추가

*               start  : 잘라낼 시작 위치   (int)

*               length : 잘라낼 문자열 길이 (int)

* 예제     : str.cut(2, 2);

*/

String.method("cut", function(start, length){

   return this.substring(0, start) + this.substr(start + length);

});

/**

* 왼쪽으로 문자열을 잘라낸다. (substring과 같은 기능이다.)

*/

String.method("left", function(len) {

return this.substring(0, len);

});


/**

* 오른쪽에서 문자열을 잘라낸다.

*/

String.method("right", function(len) {

return this.substring(this.length-len);

});

/**

* 가운데에서 문자열을 잘라낸다.

*/

String.method("mid", function(start, len) {

if ( start > 0 ) {

start = start - 1;

}

else {

throw "시작위치는 1부터 입니다.";

}

if ( len == undefined ) {

return this.substring(start);

}

return this.substring(start, start+len);

});

/**

* 문자열을 숫자로 바꿔준다.

* 숫자로 변환할수 없는 문자는 0을 리턴한다.

*/

String.method("toNumber", function() {

var num = Number(this.replace(/[,\s]/g, ""));

return (isNaN(num) ? 0 : num);

});

/**

* 숫자 부분에서 정수만 추출 하는 메소드

*/

Number.method("integer", function() {

return Math[this < 0 ? "ceiling" : "floor"](this);

});



exports.alert = function(msg) {

$.Echo(msg);

};


exports.$ = $;

})(this, WScript);









// 메인

;(function() {

alert("메인입니다.");

})();


posted by 뚱2

// false, NaN, null, undefined, "", 0 이외의 모든것은 true 이다.

(function() {

var arr = [ false, NaN, null, undefined, "", 0 ];

for (var i = 0; i < arr.length; i++) {

if ( arr[i] ) { alert(true);  }

else          { alert(false); }

}//for (var i = 0; i < arr.length; i++) {

})();


posted by 뚱2

결국 arguments의 length 속성을 이용한다.

val: function( value ) {

var hooks, ret, isFunction,

elem = this[0];


if ( !arguments.length ) {

if ( elem ) {

hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];


if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {

return ret;

}


ret = elem.value;


return typeof ret === "string" ?

// handle most common string cases

ret.replace(rreturn, "") :

// handle cases where value is null/undef or number

ret == null ? "" : ret;

}


return;

}


isFunction = jQuery.isFunction( value );


return this.each(function( i ) {

var self = jQuery(this), val;


if ( this.nodeType !== 1 ) {

return;

}


if ( isFunction ) {

val = value.call( this, i, self.val() );

} else {

val = value;

}


// Treat null/undefined as ""; convert numbers to string

if ( val == null ) {

val = "";

} else if ( typeof val === "number" ) {

val += "";

} else if ( jQuery.isArray( val ) ) {

val = jQuery.map(val, function ( value ) {

return value == null ? "" : value + "";

});

}


hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];


// If set returns undefined, fall back to normal setting

if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {

this.value = val;

}

});

}


posted by 뚱2

윈도우에서 javascript를 사용할수 있는 방법
CreateObject로 COM을 사용할수 있기때문에 조금만 머리 굴리면 웬만한건 다 될듯 하다.

 


Object Model : http://msdn.microsoft.com/ko-kr/library/a74hyyw0.aspx
링크         : http://msdn.microsoft.com/ko-kr/library/9bbdkx3k.aspx
Reference : http://msdn.microsoft.com/ko-kr/library/98591fh7.aspx
참고         : http://bybi.tistory.com/320

 

간단한 javascript 코드를 테스트 한다거나 유틸리티성 변환 프로그램을 만들때 쉽고 가볍게 만들수 있어


애용 하고 있습니다.


요즘 추세대로 익명함수를 바로 호출하여 지역화 시켜서 사용하면 편합니다.


Windows Host Script : http://www.taeyo.pe.kr/lecture/20_Tips/wsh_01.htm 


// 테스트 코드

(function($) {

var msg    = "기본신청기간(2011년 11월 01일 ~ 2012년 01월 05일 )";

var result = /.*?\((.*?)\).*?/gi.exec(msg);

if ( result != null )

{

$.Echo(result[1]);

}

})(WScript);


posted by 뚱2

참고 : http://blog.naver.com/PostView.nhn?blogId=gudejrdl102&logNo=150108479957 


// IE와 타 브라우저 호환성

function handler(event) {

    var event = event || window.event;

    var target = event.target || event.srcElement;

}


posted by 뚱2

[jQuery] PlugIn 만들기

JavaScript/jQuery 2012. 8. 8. 23:20

링크 : http://docs.jquery.com/Plugins/Authoring 

posted by 뚱2

<script type="text/javascript">

// 기존코드

if ( slt_SF_CLS.disabled == true ) {

}


// 위와 같은 코드를 아무생각 없이 jQuery를 이용해서 아래와 같이 변경했더니 안됐다.

// 이걸 어떻게 찾아 ㅡㅡ;

if ( $(slt_SF_CLS).attr("disabled") == true ) {

}


// 암튼 출력 해보면

$(slt_SF_CLS).attr("disabled", false);

alert($(slt_SF_CLS).attr("disabled"));    // undefined

$(slt_SF_CLS).attr("disabled", true);

alert($(slt_SF_CLS).attr("disabled"));    // disabled


// readonly attribute도 마찬가지 이다.

$(slt_SF_CLS).attr("readonly", false);

alert($(slt_SF_CLS).attr("readonly"));    // udefined

$(slt_SF_CLS).attr("readonly", true);

alert($(slt_SF_CLS).attr("readonly"));    // readonly

</script>


// HTML

<select id="slt_SF_CLS" name="slt_SF_CLS">

</select>


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

[jQuery] val 메소드 getter, setter 구별법  (0) 2012.08.30
[jQuery] PlugIn 만들기  (0) 2012.08.08
[jQuery] .each $.each 순회중 continue, break 하기  (0) 2012.07.26
[jQuery] ajaxForm 구현  (0) 2012.07.23
[jQuery] Plugin Validation  (0) 2012.06.18
posted by 뚱2

[CSS] Selector 셀렉터

JavaScript/CSS 2012. 8. 1. 09:09

링크 : http://www.okjsp.pe.kr/seq/197120 

 

Selector

Example

Example description

CSS

.class

.intro

class="intro" 속성을 가진 모든 엘리먼트 선택

1

#id

#firstname

id="firstname" 속성을 가진 엘리먼트 선택

1

*

*

모든 엘리먼트 선택

2

element

p

모든 <p> 엘리먼트 선택

1

element,element

div,p

모든 <div> 엘리먼트와 모든 <p> 엘리먼트 선택

1

element element

div p

<div> 내의 모든 <p> 엘리먼트 선택

1

element>element

div>p

<div> 바로 하위에 있는 모든 <p> 엘리먼트 선택

2

element+element

div+p

<div> 바로 다음에 있는 모든 <p> 엘리먼트 선택

2

[attribute]

[target]

target 속성을 갖고 있는 모든 엘리먼트 선택

2

[attribute=value]

[target=_blank]

target="_blank" 속성을 갖고 있는 모든 엘리먼트 선택

2

[attribute~=value]

[title~=flower]

"flower" 단어를 포함한 title 속성을 갖고 있는 모든 엘리먼트 선택

2

[attribute|=value]

[lang|=en]

lang 속성값이 "en"으로 시작하는 모든 엘리먼트 선택

2

:link

a:link

모든 방문하지 않은 링크 선택

1

:visited

a:visited

모든 방문했던 링크 선택

1

:active

a:active

활성화된 모든 링크 선택

1

:hover

a:hover

마우스 오버된 링크 선택

1

:focus

input:focus

포커스가 있는 <input> 엘리먼트 선택

2

:first-letter

p:first-letter

모든 <p> 엘리먼트의 첫 번째 문자 선택

1

:first-line

p:first-line

모든 <p> 엘리먼트의 첫 번째 줄 선택

1

:first-child

p:first-child

부모가 있는 모든 <p> 엘리먼트의 첫 번째 선택

2

:before

p:before

모든 <p> 엘리먼트 콘텐트의 앞에 선택

2

:after

p:after

모든 <p> 엘리먼트 콘텐트의 뒤 선택

2

:lang(language)

p:lang(it)

lang 속성값이 "it"로 시작하는 모든 <p> 엘리먼트 선택

2

element1~element2

p~ul

<p> 엘리먼트 앞에 있는 모든 <ul> 엘리먼트 선택

3

[attribute^=value]

a[src^="https"]

src 속성값이 "https"로 시작하는 모든 <a> 엘리먼트 선택

3

[attribute$=value]

a[src$=".pdf"]

src 속성값이 ".pdf"로 끝나는 모든 <a> 엘리먼트 선택

3

[attribute*=value]

a[src*="w3schools"]

src 속성값이 "w3schools" 문자열을 포함하는 모든 <a> 엘리먼트 선택

3

:first-of-type

p:first-of-type

부모가 있는 첫번째 <p> 엘리먼트인 모든 <p>엘리먼트 선택

3

:last-of-type

p:last-of-type

부모가 있는 마지막 <p> 엘리먼트인 모든 <p>엘리먼트 선택

3

:only-of-type

p:only-of-type

부모가 있는 유일한 <p> 엘리먼트인 모든 <p>엘리먼트 선택

3

:only-child

p:only-child

부모에게 유일한 자식인 모든 <p>엘리먼트 선택

3

:nth-child(n)

p:nth-child(2)

부모에게 두 번째 자식인 모든 <p>엘리먼트 선택

3

:nth-last-child(n)

p:nth-last-child(2)

부모에게 마지막에서 두 번째 자식인 모든 <p>엘리먼트 선택

3

:nth-of-type(n)

p:nth-of-type(2)

부모에게 두 번째 <p> 엘리먼트인 모든 <p>엘리먼트 선택

3

:nth-last-of-type(n)

p:nth-last-of-type(2)

부모에게 마지막에서 두 번째 <p> 엘리먼트인 모든 <p>엘리먼트 선택

3

:last-child

p:last-child

부모 안에서 마지막 자식인 모든 <p> 엘리먼트 선택

3

:root

:root

문서 루트 엘리먼트 선택

3

:empty

p:empty

하위에 아무것도 없는(텍스트마저도 없는) 모든 <p> 선택

3

:target

#news:target

현재 활성화된 #news 엘리먼트 선택(앵커 이름을 포함한 URL이 클릭된)

3

:enabled

input:enabled

모든 활성화된 <input> 엘리먼트 선택

3

:disabled

input:disabled

모든 비활성화된 <input> 엘리먼트 선택

3

:checked

input:checked

모든 체크된 <input> 엘리먼트 선택

3

:not(selector)

:not(p)

<p> 엘리먼트가 아닌 모든 요소 선택

3

::selection

::selection

사용자가 선택한 부분 선택

3

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

[CSS] Table CSS  (0) 2015.06.25
[CSS] inline, block, inline-block 차이?  (0) 2014.04.15
posted by 뚱2

/**

 * 

 * @param interval : yyyy(년), m(월), d(일)

 * @param number : 증가 년, 월, 일

 * @param dateformat : 날짜 문자열

 * @returns {String} yyyymmdd 8자리로 리턴

 */

function DateAdd(interval, number, dateformat) {

dateformat = clear_DateSTRING(dateformat);

var int_millisecond = 1;

var int_second      = 1000 * int_millisecond;

var int_minute      = 60 * int_second;

var int_hour        = 60 * int_minute;

var int_day         = 24 * int_hour;

var YY_form = CInt(Left(dateformat, 4));

var MM_form = CInt(Mid(dateformat, 5, 2))-1;

var DD_form = CInt(Right(dateformat, 2));

var date = new Date(YY_form, MM_form, DD_form);

var date_milliseconds = date.valueOf();

var add_milliseconds  = 0;

var ret_date = null;

switch (interval) {

case "yyyy":

date.setFullYear(date.getFullYear()+number, date.getMonth(), date.getDate());

ret_date = date;

break;

case "m":

date.setFullYear(date.getFullYear(), date.getMonth()+number, date.getDate());

ret_date = date;

break;

case "d":

add_milliseconds  = number * int_day;

ret_date = new Date(date_milliseconds + add_milliseconds);

break;

}

var year  = ret_date.getFullYear();

var month = ret_date.getMonth() + 1;

if ( month < 10 ) {

month = "0" + month;

}

var day   = ret_date.getDate();

if ( day < 10 ) {

day = "0" + day;

}

return ( "" + year + month + day );

}


posted by 뚱2

출처 : http://www.w3schools.com 

The JavaScript global properties and functions can be used with all the built-in JavaScript objects.


JavaScript Global Properties

PropertyDescription
InfinityA numeric value that represents positive/negative infinity
NaN"Not-a-Number" value
undefinedIndicates that a variable has not been assigned a value

JavaScript Global Functions

FunctionDescription
decodeURI()Decodes a URI
decodeURIComponent()Decodes a URI component
encodeURI()Encodes a URI
encodeURIComponent()Encodes a URI component
escape()Encodes a string
eval()Evaluates a string and executes it as if it was script code
isFinite()Determines whether a value is a finite, legal number
isNaN()Determines whether a value is an illegal number
Number()Converts an object's value to a number
parseFloat()Parses a string and returns a floating point number
parseInt()Parses a string and returns an integer
String()Converts an object's value to a string
unescape()Decodes an encoded string


posted by 뚱2

링크 : http://malsup.com/jquery/block/ 


전 ajax 통신중 대용량 비동기 통신을 할때만 걸어놨습니다.


// 기본 셋팅

$.ajaxSetup({

    type        : 'POST',

    async       : false,

    cache       : false,

    contentType : 'application/json; charset=utf-8',

    dataType    : 'json',

    error       : function(xhr,e) {

        $.unblockUI();

        if (xhr.status == 0) {

            alert('You are offline!!\n Please Check Your Network.');

        }

        else if (xhr.status == 404) {

            alert('Requested URL not found.');

        }

        else if (xhr.status == 500) {

            alert('Internel Server Error.\n');

        }

        else if (e == 'parsererror') {

            alert('Error.\nParsing JSON Request failed.');

        }

        else if (e == 'timeout') {

            alert('Request Time out.');

        }

        else {

            alert('Unknow Error.\n'+xhr.responseText);

        }

    },

    beforeSend : function(xhr, setting) {

        if ( setting && setting.async == true ) {

            $.blockUI();

        }

    },

    complete   : function(xhr, e) {

        $.unblockUI();

    }

});//$.ajaxSetup({


posted by 뚱2

링크 : http://firejune.com/1275/자바스크립트+메모리+릭+디텍터?stag=메모리+릭 

링크 : http://rhio.tistory.com/177



JSLeaksDetector.msi


posted by 뚱2

// 예)

var ADC = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$.each(ADC, function(i, rs) {

if ( rs == 5 ) {

return true; // for 문의 continue;와 같다.

}

else if ( rs == 8 ) {

return false; // for 문의 break;와 같다.

}


// ... 작업들

});


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

[jQuery] PlugIn 만들기  (0) 2012.08.08
[jQuery] .attr("disabled") .attr("readonly") 리턴값  (0) 2012.08.01
[jQuery] ajaxForm 구현  (0) 2012.07.23
[jQuery] Plugin Validation  (0) 2012.06.18
[jQuery] jQuery.type() 함수 구현해보기  (0) 2012.02.08
posted by 뚱2
자바의 import와 비슷하게 패키지 명을 입력해서 인클루드 하게 만들었습니다.

/**

* url은 문자열 배열이나 문자열이 올수 있다.

* 예) "SEED.df.DF_01.DF_HEADER_SEL"

*     ["SEED.df.DF_01.DF_HEADER_SEL", "SEED.df.DF_01.DF_HEADER"]

*/

SEED.importScript = function(url) {

var urls = [];

if ( url == undefined || url == null || url == "" ) {

return;

}

if ( $.type(url) == "string" ) {

urls.push(url);

}

else if ( $.type(url) == "array" ) {

urls = url;

}

else {

return;

}

$.each(urls, function(index, el) {

var newUrl = el.replace(/(^SEED\.)/gi, ""); // SEED가 있다면 제거한다. 

newUrl = newUrl.replace(/\./g, "/") + ".js";

var fullUrl = SEED.contextPath.get() + "/resources/js/" + newUrl;

$script = $("<script type=\"text/javascript\" charset=\"utf-8\" src=\"" + fullUrl + "\"></script>");

$script.bind("readystatechange", function() {

var $this = $(this);

if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

// FIXME : 나중에 메모리가 세는지 꼭 검사해야 한다.

// Handle memory leak in IE

this.onload = this.onreadystatechange = null;

$this.remove();

}

});

$script.appendTo("body");

});

};


posted by 뚱2

한글주소를 URL뒤에 붙이는 쿼리 스트링으로 전달하면 깨지는 경우가 발생합니다.

이럴때는 인코딩을 해줘야 합니다.



참고 : http://www.w3schools.com/jsref/jsref_obj_global.asp


위에서


FunctionDescription
decodeURI()Decodes a URI
decodeURIComponent()Decodes a URI component
encodeURI()Encodes a URI
encodeURIComponent()Encodes a URI component
escape()Encodes a string


함수를 이용하시면 됩니다.

posted by 뚱2

[jQuery] ajaxForm 구현

JavaScript/jQuery 2012. 7. 23. 00:31

사실 ajax를 이용하는게 아니라 예전부터 많이 사용하던 iframe을 이용하여 화면 깜빡임을 없애는 방식이다.


/**

 * form을 ajax로 전송한다. (파일 포함)

 */

$.fn.ajaxForm = function(handler) {

    var $this = $(this);

    if ( $this[0] && $this[0].tagName.toUpperCase() == "FORM" ) {

        //랜덤한 수를 출력

        var ranNumber = Math.floor(Math.random() * 10000) + 1;

        var strId = "";

        strId += "SEED";

        strId += "_";    

        strId += (new Date()).getTime();

        strId += "_" + ranNumber;


        $this.attr("target", strId);    

        $("<iframe id=\"" + strId + "\" name=\"" + strId + "\" />")

            .hide()

            .appendTo($this.parents("body"))

            .load(function() {

                var that = this;


                if ( $.type(handler) == "function" ) {

                    var result = $.parseJSON(window.frames[strId].document.body.innerHTML);

                    if ( result == undefined || result == null || result == "" ) {

                        result = {

                            success : false,

                            message : "결과가 존재하지 않습니다."

                        };

                    }

                    handler(result);

                }

            });

    }//if ( $this[0] && $this[0].tagName.toUpperCase() == "FORM" ) {


    return $this;

};


사용방법

(function($, exports) {$(document).ready(function() {

////////////////////////////////////////////////////////////////////////////////////

$("#myform").ajaxForm(function(result) {

    if ( result && result.success == true ) {

        alert(result.message);

    }

});

////////////////////////////////////////////////////////////////////////////////////

});})(jQuery, window);



참고 : http://hanjiq.egloos.com/2373084 

posted by 뚱2

자바스크립트는 선언되지 않는 변수에 값을 할당하면은 자동적으로 글로벌에 생성됩니다.

 

다만 선언되지 않은 변수를 사용하면 런타임에러가 발생합니다.

 

그리고 정의 되었지만 값을 할당한 적이 없는 경우는 undefined가 리턴됩니다.

 

또한 객체의 정의되지 않는 property를 읽을때도 undefined가 리턴됩니다.

 

참고 : 자바스크립트 완벽 가이드

// 현재 값은 undefined
var no_init; 
// 선언되지 않은 변수를 사용했기 때문에 에러가 발생
alert(u); 
//선언되지 않은 변수에 값을 할당하려 하는 순간 이 변수가 생성된다.
u = 3;

posted by 뚱2

링크 : http://luvstudy.tistory.com/13 

posted by 뚱2

[Javascript] DateAdd

JavaScript/JavaScript 2012. 7. 14. 22:22
// 예 add_DATEs("2012-12-31", 3) 이면 2013-01-03을 리턴
function add_DATEs(dateformat, dates) {
	dateformat = clear_DateSTRING(dateformat);
	var int_millisecond = 1;
	var int_second      = 1000 * int_millisecond;
	var int_minute      = 60 * int_second;
	var int_hour        = 60 * int_minute;
	var int_day         = 24 * int_hour;
	
	var YY_form = CInt(Left(dateformat, 4));
	var MM_form = CInt(Mid(dateformat, 5, 2))-1;
	var DD_form = CInt(Right(dateformat, 2));
	
	var date = new Date(YY_form, MM_form, DD_form);
	var date_milliseconds = date.valueOf();
	var add_milliseconds  = dates * int_day;
	var ret_date = new Date(date_milliseconds + add_milliseconds);
	
	var year  = ret_date.getFullYear();
	var month = ret_date.getMonth() + 1;
	if ( month < 10 ) {
		month = "0" + month;
	}
	var day   = ret_date.getDate();
	if ( day < 10 ) {
		day = "0" + day;
	}
	
	return ( "" + year + month + day );
}
posted by 뚱2

참고 : http://codemuri.tistory.com/756 

자바스크립트는 기본적으로 탐욕적 수량자이다.


1. 탐욕적 수량자와 게으른 수량자


 탐욕적 수량자게으른 수량자 
 * *? 
 + +? 
 {n,} {n,}? 

posted by 뚱2

참조 : JavaScript Patterns 에서 발췌


//=======================================================================
// SEED Class 영역
//=======================================================================
var SEED = SEED || {};

/**
 * 네임스페이스를 생성한다.
 * @param ns_string
 */
SEED.ns = function(ns_string) {
	var parts = ns_string.split("."),
		parent = SEED,
		i;
	
	// 처음에 중복되는 전역 객체명은 제거한다.
	if ( parts[0] === "SEED" ) {
		parts = parts.slice(1);
	}
	
	for (i = 0; i < parts.length; i++) {
		// 프로퍼티가 존재하지 않는다면 생성한다.
		if ( typeof parent[parts[i]] === "undefined" ) {
			parent[parts[i]] = {};
		}
		
		// 자식들을 검사하기 위해서 현재 나를 부모로 만든다.
 		parent = parent[parts[i]];
	}
	
	return parent;
};

// 사용예
var module2 = SEED.ns("SEED.modules.modules2");
module2 === SEED.modules.module2;//true

posted by 뚱2

[html] dd, dt, dl

JavaScript/Html 2012. 6. 22. 13:36

링크 : http://polinah.blog.me/50134577072 

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

[html] Zen Coding 링크  (0) 2012.09.23
[html] http 프로토콜  (0) 2012.02.16
[html] html 특수문자 태그  (0) 2011.08.18
[html] map 사용  (0) 2011.07.22
posted by 뚱2

[jQuery] Plugin Validation

JavaScript/jQuery 2012. 6. 18. 09:59

다운로드 : http://bassistance.de/jquery-plugins/jquery-plugin-validation/


링크 : http://mytory.co.kr/archives/195 

posted by 뚱2

/**

 * obj  : url or json data

 * data : json data

 */

my.submitWithJson = function(obj, data, target, method) {

    try {

        var param = null;       

        // json object이라면

        if ( obj && Object.prototype.toString.call(obj) === '[object Object]' ) {

            param = {

                 'url'     : obj.url                 || ''

                ,'data'    : obj.data                || {}

                ,'target'  : obj.target              || '_self'

                ,'method'  : obj.method              || 'POST'

            };

        }

        else {

            param = {

                 'url'     : obj                     || ''

                ,'data'    : data                    || {}

                ,'target'  : target                  || '_self'

                ,'method'  : method                  || 'POST'

            }; 

        }

         

        //랜덤한 수를 출력

        var curDate   = new Date();

        var ranNumber = Math.floor(Math.random() * 10000) + 1;

        var strId = "";

            strId += param.target;

            strId += "_";           

            strId += curDate.getFullYear();

            strId += curDate.getMonth();

            strId += curDate.getDay();

            strId += curDate.getHours();

            strId += curDate.getMinutes();

            strId += curDate.getSeconds();

            strId += "_" + ranNumber;

             

        var $newForm = jQuery("<form></form>")

                        .attr("name"  , strId)

                        .attr("id"    , strId)

                        .attr("method", param.method);

        if ( $newForm ) {

            if ( Object.prototype.toString.call(param.data) === "[object Array]") {

                jQuery.each(param.data, function(index, val) {

                    var row = val;

                    jQuery.each(row, function(key, val) { 

                        jQuery("<input type='"hidden"'>")

                            .attr("name" , key)

                            .attr("value", val)

                            .appendTo($newForm);

                    });

                });

                $newForm.appendTo(document.body);

            }

            else {

                jQuery.each(param.data, function(key, val) { 

                    jQuery("<input type='"hidden"'>")

                        .attr("name" , key)

                        .attr("id"   , key)

                        .attr("value", val)

                        .appendTo($newForm);

                });

                $newForm.appendTo(document.body);               

            }

     

            var myForm = $newForm[0];

            myForm.action = param.url;

            myForm.method = param.method;

            myForm.target = param.target;

             

            myForm.submit();

            $newForm.remove();

        }//if ( $popForm ) {

    }

    catch (e) {alert(e.message);}

    finally   {}

}; 


posted by 뚱2