'Language/JAVASCRIPT'에 해당되는 글 106건

  1. 2011.08.09 자바스크립트 맵, javaScript Map
  2. 2011.08.09 클래스명으로 엘리멘트 얻기, getElementsByClassName()
  3. 2011.07.27 자바스크립트(javascript) 배열(array) 사용
  4. 2011.07.25 [javascript] typeof 연산자 ExtJS / WEB2.0
  5. 2011.07.13 User Agent 파헤치기 (navigator.userAgent)
  6. 2011.06.14 firefox, IE 이벤트(event) 얻기
  7. 2011.06.14 자바스크립트 이벤트 키코드표(keyCode )
  8. 2011.06.09 xml 파서
  9. 2011.05.13 쿠키 / 팝업 생성
  10. 2011.05.11 주민번호로 나이/성별 구하기

자바스크립트 맵, javaScript Map

Language/JAVASCRIPT 2011. 8. 9. 11:36

var Map = function(){
this.map = new Object();
};

Map.prototype = {
put : function(key, value){
this.map[key] = value;
},
get : function(key){
return this.map[key];
},
containsKey : function(key){
return key in this.map;
},
containsValue : function(value){
for(var prop in this.map){
 if(this.map[prop] == value) return true;
}
return false;
},
isEmpty : function(key){
return (this.size() == 0);
},
clear : function(key){
delete this.map[key];
},
clearAll : function(){
for(var prop in this.map){
delete this.map[prop];
}
},
remove : function(key){
delete this.map[key];
},
keys : function(){
var keys = new Array();
for(var prop in this.map){
keys.push(prop);
}
return keys;
},
values : function(){
var values = new Array();
for(var prop in this.map){
values.push(this.map[prop]);
}
return values;
},
size : function(){
var count = 0;
for (var prop in this.map) {
count++;
}
return count;
}
};
:

클래스명으로 엘리멘트 얻기, getElementsByClassName()

Language/JAVASCRIPT 2011. 8. 9. 11:34
IE에서는 document.getElementsByClassName();을 지원하지 않음

function getElementsByClassName(className) {
   var arrNode = new Array();
   var elements = document.getElementsByTagName('*');

   for (var i = 0; i < elements.length; i++) {
  var tmpClassName = elements[i].getAttribute('className');
  if(className==tmpClassName){
arrNode.push(elements[i]);
  }
   }

   return arrNode;
}
:

자바스크립트(javascript) 배열(array) 사용

Language/JAVASCRIPT 2011. 7. 27. 14:27

1. 배열생성

var array_test = new Array();

 

2. push 메소드 사용

Definition and Usage

The push() method adds new elements to the end of an array, and returns the new length.

Note: This method changes the length of an array!

Syntax

array.push(element1, element2, ..., elementX)

ParameterDescription
element1, element2, ..., elementX Required. The element(s) to add to the end of the array

Example

Example

Add new elements to the end of an array, and return the new length:

<script type="text/javascript">

var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.push("Kiwi") + "<br />");
document.write(fruits.push("Lemon","Pineapple") + "<br />");
document.write(fruits);

</script>

The output of the code above will be:

5
7
Banana,Orange,Apple,Mango,Kiwi,Lemon,Pineapple

 

 

3. join 메소드 사용

Definition and Usage

The join() method joins all elements of an array into a string, and returns the string.

The elements will be separated by a specified separator. The default separator is comma (,).

Syntax

array.join(separator)

ParameterDescription
separator Optional. The separator to be used. If omitted, the elements are separated with a comma

Example

Example

Join all elements of an array into a string:

<script type="text/javascript">

var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.join() + "<br />");
document.write(fruits.join("+") + "<br />");
document.write(fruits.join(" and "));

</script>

The output of the code above will be:

Banana,Orange,Apple,Mango
Banana+Orange+Apple+Mango
Banana and Orange and Apple and Mango

 

 

출처 - http://www.w3schools.com/jsref/jsref_obj_array.asp

 

JavaScript Array Object


Array Object

The Array object is used to store multiple values in a single variable.

For a tutorial about Arrays, read our JavaScript Array Object tutorial.


Array Object Properties

PropertyDescription
constructor Returns the function that created the Array object's prototype
length Sets or returns the number of elements in an array
prototype Allows you to add properties and methods to an object

Array Object Methods

MethodDescription
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf()  
join() Joins all elements of an array into a string
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the new length
valueOf() Returns the primitive value of an array


- 출처 : http://blog.naver.com/fromyongsik

:

[javascript] typeof 연산자 ExtJS / WEB2.0

Language/JAVASCRIPT 2011. 7. 25. 15:23
 

typeof 연산자는 형식 정보를 문자열로 반환하며 
"Number", "String", "Boolean", "Object", "Function", "undefined"라는
6가지 형식을 반환할 수 있습니다.


선택적인 요소로 
typeof 구문에 괄호를 사용할 수도 있기에 다음 
둘 중 한 가지 방법으로
사용할 수 있습니다.

1. typeof operand
2. typeof (operand)

 

if ( typeof(object) != "Object" ) {

alert('객체가 아닙니다.');

}

if ( typeof 'AAA'  != 'Number' ) {

alert('숫자가 아닙니다.');

}

 

또다른 예를 들어 우리가 이런 변수를 정의했다고 해봅시다.

  • var myFun = new Function("5+2");
    var shape="round";

    var size=1;

    var today=new Date()
typeof는 이 변수들에 대해서 다음과 같은 결과를 반환할 것입니다. 
  • typeof myFun is function
    typeof shape is string

    typeof size is number

    typeof today is object

    typeof dontExist is undefined

true와 null 키워드에 대해서 typeof 연산자는 다음과 같은 결과를 반환합니다.

  • typeof true is boolean
    typeof null is object

수와 문자열에 대해서 typeof 연산자는 다음과 같은 결과를 반환합니다.

  • typeof 62 is number
    typeof 'Hello world' is string

속성 값에 대해서 typeof 연산자는 속성이 포함하고 있는 값의 형식을 반환합니다.

  • typeof document.lastModified is string
    typeof window.length is number
    typeof Math.LN2 is number

메소드와 함수에 사용하면 typeof 연산자는 다음과 같은 결과를 반환합니다.

  • typeof blur is function
    typeof eval is function
    typeof parseInt is function
    typeof shape.split is function

미리 정의된 개체들에 대해서 typeof 연산자는 다음과 같은 결과를 반환합니다.

:

User Agent 파헤치기 (navigator.userAgent)

Language/JAVASCRIPT 2011. 7. 13. 17:45
발생일: 2011.01.31

문제:
크로스 브라우저 처리를 위해 navigator.userAgent 프로퍼티를 보고 있다.
아래 문자열은 지금 사용하고 있는 Firefox의 userAgent 값이다.

"Mozilla/5.0 (Windows; U; Windows NT 6.1; ko; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 IPMS/A640400A-14D460801A1-000000426571"

참고 삼아 다른 사이트와 라이브러리 소스를 보다 보니, 어떤 사이트에서는 "Gecko" 문자열을 찾아 브라우저별 구현을 나눴고, 다른 라이브러리에서는 "Firefox" 문자열을 찾아 구현해놨다. 음...

크롬이나 사파리에서 userAgent를 찍어보면, "link Gecko"라고 되어있기도 하다. 음...

userAgent에 대해 확실하게 정리를 해봐야겠다.


해결책:
1. Navigator 객체는?
navigator 객체는 브라우저의 종류와 버전 등 웹브라우저 전반에 대한 정보를 제공하는 객체이다.

navigator라는 객체 이름은 Netscape Navigator 브라우저에서 온 것이며, IE의 경우 벤더 중립적인 표현으로 clientInformation을 지원하기도 한다. 실제로 IE에서 navigator === clientInformation 을 실행하면 true를 반환한다.

naviagtor에는 대표적으로 다음과 같은 프로퍼티있다.

navigator.appName
브라우저의 간단한 이름
navigator.appVersion
버전 또는 버전과 관련된 정보. 브라우저 내부적으로 사용되는 버전에 대한 숫자이므로 사용자에게 표시되는 버전 숫자와 항상 일치하지는 않다.
navigator.userAgent
브라우저가 User-Agent HTTP 헤더에 넣어 전송하는 문자열로 appName과 appVersion의 모든 정보를 포함하며 더 자세한 정보를 추가로 담고 있다. 이 정보에 대해서는 표준화된 서식이 존재하지 않기 때문에 각 브라우저 특성에 따라 파싱해야 한다.
navigator.appCodeName
브라우저의 코드 네임. Netscape에서는 "Mozilla"라는 코드 네임을 사용한다. 호환성을 위해 IE도 역시 같은 코드 네임을 사용한다. 
navigator.platform
브라우저가 실행되는 하드웨어 플랫폼으로 javascript 1.2 버전부터 지원한다.


navigator 객체의 프로퍼티가 알려주는 정보는 완전히 신뢰할 수 있는 것이 아니다.
예를 들어, Firefox 1.0에서 appName은 "Netscape"로, appVersion은 "5.0"으로 시작한다.
모질라 코드에 기반하지 않은 사파리 브라우저에서도 똑같은 값이 반환된다.
IE 6.0에서는 마찬가지로 appName이 "Mozilla"로, appVersion은 "4.0"으로 시작한다.
이는 오래 전에 배포된 브라우저 탐지 코드들이 아주 많기 때문에, 이 프로퍼티들을 갱신하면 수 많은 웹페이지들의 호환성이 깨지게 되고, 이를 브라우저 제작사가 감당할 수 없기 때문이라고 한다. (더 자세한 이유는 아래 히스토리 참고)


2. History of User Agent
navigator.userAgent에 대해 더 깊게 이해하려면, User Agent에 대한 히스토리를 알아두는 게 도움이 될 수 있다.

User-Agent 헤더의 탄생
1995년 HTML 2.0이 나오기 전까지 HTML은 표준화되지 않았다.
당시 Netscape나 Microsoft 같은 벤더들은 웹제작자들이 좀 더 풍부하게 컨텐츠를 제공할 수 있도록 각자 매력적인 기능을 추가하고 있었다. 이에 따라 다양한 브라우저가 출시되기 시작했고, 최신 브라우저는 좀 더 화려한 HTML을 제공했다.
여러 브라우저가 출시되면서 웹제작자들은 제작한 컨텐츠가 다양한 브라우저에 모두 정상적으로 보일 수 있도록 대책이 필요했다. 그 중 하나는 가장 낮은 버전의 HTML을 제공하는 것이었고, 다른 하나는 브라우저의 버전을 탐지해 서버가 브라우제 따라 적합한 컨텐츠를 내려주도록 하는 것이었다. 당시에는 브라우저에서 스크립트가 가능하지 않았기 때문에, 서버에서 브라우저를 탐지해내기 위해 User-Agent 헤더가 생기게 됐다.


"Mozilla/version",  오해의 시작
당시 브라우저는 Netscape Navigator와 Internet Explorer 뿐이었기 때문에, 브라우저를 탐지하기 위해 User Agent의 vendor와 version을 구분하는 것만으로 충분했다.

Netscape 브라우저는 "Mozilla/version" 과 같은 방식으로 코드 네임과 버전을 표시하고, 그 뒤로 추가적인 정보를 기술했다. 따라서 최초의 브라우저 탐지 기법은 userAgent에서 Mozilla/version 정보를 찾는 방식이었다.
이후의 다른 브라우저 벤더들은 자사 제품이 Netscape 브라우저의 특정 버전과 호환된다는 의미로 userAgent 정보에 Mozilla/version 을 추가했다. 실제로는 "Mozilla/version" 기반이 아니었지만 말이다.

당시 Netscape의 점유율이 가장 높았던 것을 생각하면 어쩌면 당연한 일이기도 하겠지만, 지금에 와서도 정확한 브라우저 여부를 탐지하는 것이 어려운 것은, 이 때 잘못된 이해와 표준화 되지 않은 방법으로 버전 정보를 기술한 것이 발단이 된 것으로 볼 수 있다. (호환성을 위해 지금까지도 대부분의 브라우저의 userAgent가 Mozilla/verion 의 형태로 시작한다.)


클라이언트 측 스크립트 출현
Netscape Navigator2 버전이 출시하면서 브라우저는 클라이언트 측 스크립트를 제공했고, 다른 브라우저들도 각자의 방식으로 스크립트를 구현하기 시작했다. 이제 웹제작자들은 서버측에서 User-Agent 헤더값으로 브라우저를 판별하지 않고, 클라이언트에서 바로 어떤 브라우저에서 접속했는지 찾아낼 수 있었다. 브라우저마다 스크립트의 구현 방법이 달랐기 때문에 웹제작자들은 document.images 같은 "객체 기반 탐지"로 브라우저를 구별해낼 수 있었다. 

이런 "객체 기반 탐지"가 많이 사용되었음에도 몇몇 웹자작자들은 vendor/version 접근법을 사용했다.
브라우저에서 navigator 객체도 제공했기 때문에, 이전에 서버에서 사용한 것과 같은 로직을 클라이언트에도 적용할 수 있었다. 게다가 navigator 객체에서는 appName과 appVersion을 따로 제공했기 때문에 vendor/version 값을 바로 알아낼 수 있었다.

Netscape Navigator4 버전과 Internet Explorer4 버전부터 HTML을 클라이언트에서 직접 조작할 수 있게 되었다. (DHTML)
더불어 CSS 스타일도 제공하기 시작했다. 이 시기의 브라우저에서는, 같은 벤더임에도 이전 버전과도 호환되지 않는 기능들이 추가되기도 했다.

스크립트가 그랬던 것처럼, 각 브라우저 벤더들의 DHTML 구현 방식이 달랐기 때문에, 웹제작자들은 브라우저 여부를 판단하기 위해 "객체 탐지 기법"을 주로 사용하게 됐다. 예를 들어, document.layers 객체가 존재하면 Netscape4 라는 것을, document.all 이 존재하면 Explorer4 버전이란 걸 쉽게 알 수 있었다. 물론 이 방법은 Netscape 와 Explorer 두 가지의 브라우저가 있을 때에만 가능한 일이었다.

vendor/version 으로 브라우저를 구별해내는 방법은 Gecko와 같은 다른 브라우저들이 나오면서 더 이상 의미가 없어졌다. vendor/version 단위로 브라우저를 구별해내는 방식은 제대로 작동하지도 않을 뿐더러, 유지보수하기도 어려웠다.


진짜 Mozilla/5.0 - Netscape6
Netscape6 는 최초의 Gecko 기반 상용 브라우저이며 Netscape6의 userAgent 값은 HTTP 표준을 따라,
"Mozilla/5.0 (...) Gecko/20001108" 과 같은 형태로 기술되었다.

첫 번째의 vendor/version 인 Mozilla/5.0 문구는 "Netscape6이 5세대 브라우저이며, 기존 브라우저와는 같지 않다"는 걸 나타낸다.
하지만 앞서 언급했듯이, 다른 브라우저들은 "호환성의 의미"로 첫 번째 버전을 Mozilla/5.0 이라고 표시한다.
따라서 Mozilla/5.0 구문만으로는 유일하게 Gecko라는 걸 판단할 수 없다.

두 번째 vendor/version 인 Gecko/20001108 은 Netscape6가 Gecko의 2000년 11월 8일 버전으로 구현됐다는 문구이다. 만약, 브라우저가 실제로 Gecko 기반인지를 확인하려 한다면 Gecko/CCYYMMDD 형태를 검색해보면 된다.

세 번째 vendor/version 인 Netscape6/6.0 은 이 브라우저가 Netscape6라는 걸 나타낸다. Netscape6의 경우, 벤더명에 버전명을 포함시켰기 때문에 효율적이지 않아 7버전부터는 벤더명에서 버전을 제외하여 아래와 같이 제공된다.
Mozilla/5.0 (...) Gecko/200207XX Netscape/7.0

따라서 기존의 vendor/version 기반 탐색을 Netscape4와 IE4에서만 가능했다.
document.all과 document.layers로 구분했던 객체 기반 탐지 방법도 Netscape6+ 와 IE5+ 가 출시되면서 더욱 복잡해졌다.


3. 각 브라우저 별 User Agent 정보
Firefox
Firefox는 아래와 같은 형태로 User Agent 정보를 제공한다.

Mozilla/5.0 (Windows; U; Windows NT 6.1; ko; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 IPMS/A640400A-14D460801A1-000000426571

- Mozilla/5.0 : 모질라 5.0 기반이다.
- platform: 플랫폼 정보
- rv: Gecko 레이아웃 엔진의 배포 버전
- Gecko/yyyymmdd : Gecko의 개발용 배포일로 yyyymmdd 형태이다. 실제 배포일은 아니며, 추후 삭제될 수 있다.
- Firefox/appversion : Firefox 의 버전이다. 


Internet Explorer
IE는 아래와 같은 형태로 User Agent 정보를 제공한다.

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; IPMS/A640400A-14D460801A1-000000426571; TCO_20110131100426; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; Tablet PC 2.0)

- Mozilla/4.0 : Mozilla 4.0과 "호환 가능"하다.
- MSIE 8.0 : Internet Explorer 8.0이다.
- Trident/4.0 : Trident 레이아웃 엔진 4.0 버전으로 구현됐다.


Chrome
Chrome의 User Agent 정보는 좀 복잡하다.

Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7

- Mozilla/5.0 : Mozilla 5.0과 호환 가능하다.
- AppleWebKit/version (KHTML, like Gecko) : "Gecko 같은" 브라우저 레이아웃 엔진인 KHTML을 사용한다.
Webkit은 KHTML를 기반으로 한 엔진이다.
- Chrome/version : Chrome이며 해당 버전이다.
- Safari/version : Safari의 해당 버전과 비슷하다.


Safari
Chrome과 거의 동일하지만 버전 정보를 포함하고 있다.

Mozilla/5.0 (Windows; U; Windows NT 6.1; ko-KR) AppleWebKit/533.18.1 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5


Opera
Opera는 가장 깔끔하다.

Opera/9.80 (Windows NT 6.1; U; ko) Presto/2.6.30 Version/10.62

- Opera/version : Opera 해당 버전이다.
- Presto/version : Presto 레이아웃 엔진을 사용하고 있다.


4. 결론
User Agent 정보는 브라우저마다 각각 다르게 제공하고 있으며, 이를 정확하게 파싱하는 것은 더욱 어려워졌다.
의미가 잘못 전달되어 작성된 "Mozilla/version" 정보는 이제는 거의 의미가 없으며, 신규 브라우저의 지나친 정보도 정확한 브라우저 탐지를 어렵게 한다.

브라우저 탐지를 위해서는 일단 "브라우저와 레이아웃 엔진과의 관계"를 알아두는 게 좋겠고, 각 브라우저 별 User Agent 정보 간 차이점을 파악해야겠다.
꼭 필요한 경우가 아니라면 "객체 기반 탐지"로 크로스 브라우저를 구현하는 걸 권장한다.


5. 참고자료
Browser Detection and Cross Browser Support(MDN) : User Agent의 히스토리와
Gecko의 User Agent 정보
Gecko user agent string reference(MDN) : MDN의 User Agent 레퍼런스
Understanding User-Agent Strings(MSDN) : MDSN의 User Agent 레퍼런스
History of the browser user-agent string : 브라우저 User Agent 정보의 히스토리
브라우저 정보에 나오는 Mozilla의 의미 : 위 포스트를 기반으로 아주 이해하기 쉽게
작성한 포스트!


:

firefox, IE 이벤트(event) 얻기

Language/JAVASCRIPT 2011. 6. 14. 14:32


<script type="text/javascript">
<!--
 function test(e){
  var eSrc = e || window.event;
  var srcET = eSrc.srcElement ? eSrc.srcElement : eSrc.target;
  
  var _event = eSrc.type;
  alert(_event);

  var _type = srcET.type;
  alert(_type);

  var _tagName = srcET.tagName;
  alert(_tagName);

 }
//-->
</script>


<input type="button" name="name:input" id="inp" value="asdf" dtype="option" onclick="test(event)">

'Language > JAVASCRIPT' 카테고리의 다른 글

[javascript] typeof 연산자 ExtJS / WEB2.0  (0) 2011.07.25
User Agent 파헤치기 (navigator.userAgent)  (0) 2011.07.13
자바스크립트 이벤트 키코드표(keyCode )  (0) 2011.06.14
xml 파서  (0) 2011.06.09
쿠키 / 팝업 생성  (0) 2011.05.13
:

자바스크립트 이벤트 키코드표(keyCode )

Language/JAVASCRIPT 2011. 6. 14. 14:24

JavaScript event.keyCode 자바스크립트 이벤트 키코드표

---------------------------------------
키코드표
---------------------------------------
←(백스페이스) = 8
TAB = 9
ENTER = 13
SHIFT = 16
CTRL = 17
ALT = 18
PAUSEBREAK = 19
CAPSLOOK = 20
한/영 = 21
한자 = 25
ESC = 27
스페이스 = 32

PAGEUP = 33
PAGEDN = 34
END = 35
HOME =36
←(중간) = 37
↑(중간) = 38
→(중간) = 39
↓(중간) = 40
INSERT = 45
DELETE = 46

0 = 48
1 = 49
2 = 50
3 = 51
4 = 52
5 = 53
6 = 54
7 = 55
8 = 56
9 = 57

A = 65
B = 66
C = 67
D = 68
E = 69
F = 70
G = 71
H = 72
I = 73
J = 74
K = 75
L = 76
M = 77
N = 78
O = 79
P = 80
Q = 81
R = 82
S = 83
T = 84
U = 85
V = 86
W = 87
X = 88
Y = 89
Z = 90

윈도우(왼쪽) = 91
윈도우(오른쪽) = 92
기능키 = 93

0(오른쪽) = 96
1(오른쪽) = 97
2(오른쪽) = 98
3(오른쪽) = 99
4(오른쪽) = 100
5(오른쪽) = 101
6(오른쪽) = 102
7(오른쪽) = 103
8(오른쪽) = 104
9(오른쪽) = 105

.(오른쪽) = 110
/(오른쪽) = 111
*(오른쪽) = 106
+(오른쪽) = 107
-(오른쪽) = 109

F1 = 112
F2 = 113
F3 = 114
F4 = 115
F5 = 116
F6 = 117
F7 = 118
F8 = 119
F9 = 120
F10 = 121
F11 = 122
F12 = 123

NUMLOCK = 144
SCROLLLOCK = 145
=(중간) = 187
-(중간) = 189
`(왼쪽콤마) = 192
\(중간) = 220

'Language > JAVASCRIPT' 카테고리의 다른 글

User Agent 파헤치기 (navigator.userAgent)  (0) 2011.07.13
firefox, IE 이벤트(event) 얻기  (0) 2011.06.14
xml 파서  (0) 2011.06.09
쿠키 / 팝업 생성  (0) 2011.05.13
주민번호로 나이/성별 구하기  (0) 2011.05.11
:

xml 파서

Language/JAVASCRIPT 2011. 6. 9. 10:57
<script type="text/javascript">
<!--
function getXMLObject() {
    var xDoc = null;
        // 파이어폭스
        if (document.implementation && document.implementation.createDocument) {
            xDoc = document.implementation.createDocument("","",null);
        // 익스플로러
        }else if (typeof ActiveXObject != "undefined") {
            var msXmlAx = null;
            try {
               //최신버젼
               msXmlAx = new ActiveXObject("Msxml2.DOMDocument");
            }catch (e){
               //구 버젼
               msXmlAx = new ActiveXObject("Msxml.DOMDocument");
            }
        xDoc = msXmlAx;
        }
    return xDoc;
}


 var objXdoc  = getXMLObject();
 objXdoc.async = false;
 objXdoc.load('xml2.xml');


 var XmlDoc = objXdoc.getElementsByTagName('item');
 document.write(XmlDoc[0].getAttribute("name"));
 document.write("<br />");
 document.write(XmlDoc[0].getElementsByTagName('title')[0].firstChild.data);

//-->
</script>




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

<?xml version="1.0" encoding="utf-8"?>
<product>
    <item name="1">
        <title>a</title>
        <etime>b</etime>
        <stime>c</stime>
        <img>d</img>
        <link>e</link>
    </item>
    <item name="2">
        <title>aa</title>
        <etime>b</etime>
        <stime>c</stime>
        <img>d</img>
        <link>e</link>
    </item>
    <item name="3">
        <title>aaa</title>
        <etime>b</etime>
        <stime>c</stime>
        <img>d</img>
        <link>e</link>
    </item>
</product>


:

쿠키 / 팝업 생성

Language/JAVASCRIPT 2011. 5. 13. 10:57


쿠키 생성 코드(팝업창으로 띄울 페이지에 아래의 코드가 들어가 있어야 합니다.)

//쿠키 생성 함수정의
function setCookie( name, value, expiredays )  {
   var todayDate = new Date();
   todayDate.setDate( todayDate.getDate() + expiredays );
   document.cookie!! = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
 }
 
 //오늘하루이창보지않음 체크시 창을 닫고 쿠키를 생성
function closeWin()  {
    setCookie( "js", "done" , 1);
    self.close();
 }

 

 

팝업창을 생성하는 HTML 페이지에 필요한 스크립트 코드

// 팝업창 생성 코드

function popup() {
    winopen=window.open('popup.html','winopen','width=500 ,height=500, left=10, top=10,  넓이,scrollbars=no');
 }

 

 

//쿠키 검사 함수 정의
function getCookie(name) {
    var prefix = name + "=";
    var cookieStartIndex = document.cookie!!.indexOf(prefix);


    if (cookieStartIndex == -1) return null;
    var cookieEndIndex = document.cookie!!.indexOf(";", cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1) cookieEndIndex = document.cookie!!.length;


    return unescape(document.cookie!!.substring(cookieStartIndex + prefix.length, cookieEndIndex));
 }


 

//쿠키가 존재하지 않으면 팝업창을 연다.
if(getCookie("js")==null)  { popup(); }

 

:

주민번호로 나이/성별 구하기

Language/JAVASCRIPT 2011. 5. 11. 15:06
function calc(jumin1, jumin2)
{
  var ssn1, ssn2;
  var nByear, nTyear;
  var today;
  ssn1 = jumin1;
  ssn2 = jumin2;

  today = new Date();
  nTyear = today.getFullYear();
 
  if (parseInt(ssn2.substring(0,1), 10) < 3){
    nByear = 1900 + parseInt(ssn1.substring(0,2), 10);

  }else{
    nByear = 2000 + parseInt(ssn1.substring(0,2), 10);

  }
  nAge = nTyear - nByear;

  nSex = parseInt(ssn2.substring(0,1), 10);

  if(nSex % 2 == 1)
    Sex = "m";
  else
    Sex ="w";
}
: