출처: http://www.quirksmode.org/dom/events/index.html

Event compatibility tables

Last updated on 22 February 2009.

See section 7B of the book.

Microsoft documentation.

Mozilla documentation. Be sure to study the "Other events", too.

Safari has always referred to my compatibility tables for more JavaScript information, so you’re currently reading the Safari documentation.

Opera documentation; unfortunately the events are summed up on a per-tag basis.

W3C DOM Events specification. Unfortunately it does not always pay attention to the current implementation of the events in the browsers.

On this page I give a quick overview of events browser compatibility.

I assume that you know the three event registration models (traditional, W3C and Microsoft) as well as event bubbling and capturing.

I spent most of my time on the cross-browser events; the links in the first compatibility table lead to even more compatibility tables with detailed information about these events.

I merely tested basic browser support for the Microsoft and W3C events without delving too deeply into the details.

Cross-browser events

Definition: cross-browser events are supported by IE and at least two of the following three browsers: Firefox, Safari, Opera.

All bugs noted in the table below are explained on the detail pages. I haven’t tested the load and unload events yet; they’ll be added to the table later on.

See the iPhone Events blog entry for more information on events on the iPhone.

Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7

When an element loses the focus.

Yes Too many Yes Incomplete Almost Incomplete Almost Too many Incomplete
  • Firefox 2 and Opera fire too many events in a variety of circumstances and also incorrectly bubble them.
  • Safari and Chrome don’t support these events on links and/or form fields in all circumstances.
  • Safari iPhone does not fire the event when the window loses the focus.
  • Konqueror doesn’t support these events on the browser window.

When a form field value changes.

Buggy Yes Yes Yes Incomplete Incomplete
  • IE has a serious bug in its handling of this event on checkboxes and radios.
  • IE, Opera, and Konqueror have a serious bug in their handling of this event when the user uses the keyboard to change a select.

When a mousedown and mouseup event occur on the same element OR an element is activated by the keyboard.

Yes Yes Yes Yes Yes Yes
  • The iPhone fires the mousedown, mouseup and click events in the correct order on a click (tap), but it either fires all three or none at all. See mousedown.
Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7

When the user right-clicks to get the context menu.

Yes Buggy Yes Buggy Yes Untestable Yes No No

Preventing the default (i.e. preventing the context menu from appearing) is the whole point of this event.

  • IE8rc1 always prevents the default when this event is handled on the document.
  • To prevent the default in Firefox 3 you have to cancel the event bubbling.

When text is copied.

Yes No Buggy Yes Untestable Yes No No
  • Firefox 3 has a lazy implementation.

When text is cut.

Yes No Buggy Yes Untestable Yes No No
  • Firefox 3 has a lazy implementation.

When two click events take place on the same element within a reasonable timeframe.

Yes Yes Yes No Yes Yes No

When the browser encounters a JavaScript error or a non-existent image file.

Almost Almost Incomplete Incomplete Incomplete Incomplete
  • IE and Firefox have trouble with JavaScript errors in the traditional event registration model.
  • Safari, Chrome, Opera and Konqueror do not support this event on JavaScript errors.
Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7

When an element receives the focus.

Yes Too many Incomplete Almost Incomplete Almost Too many Incomplete
  • Firefox 2 and Opera fire too many events in a variety of circumstances and also incorrectly bubble them.
  • Firefox fires a focus event whenever you click on the document.
  • Safari and Chrome don’t support these events on links and/or form fields in all circumstances.
  • Safari iPhone does not fire the event when the window gains the focus.
  • Konqueror doesn’t support these events on the browser window.

When the user depresses a key.

Yes Yes Yes Yes Minimal Incomplete

The event should continue firing as long as the user keeps the key depressed.

  • The keydown event does not repeat in Opera and Konqueror.
  • You cannot prevent the default onkeydown in Opera.
  • On the iPhone it’s not possible to repeat a character by keeping a key depressed.

When a keystroke leads to a character being added to an HTML element.

Yes Too many Too many Yes No Yes Too many Too many

This event should fire only if a keystroke leads to a character actually being added to an HTML element such as a text input. It should not fire when the user presses keys like the arrow keys which do not result in a character.

The event should continue firing as long as the user keeps the key depressed.

  • Firefox, Safari 3.0, Opera and Konqueror fire keypress events on any key.

When the user releases a key.

Yes Yes Yes Yes Yes Yes

This event fires after the keystroke has been processed; for instance after a character has been added to a text input. It’s not possible to cancel the default action because that action has already taken place. This event should not repeat.

Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7

When the user depresses a mouse button.

Yes Yes Yes Yes Yes Yes
  • The iPhone fires the mousedown, mouseup and click events in the correct order on a click (tap), but it either fires all three or none at all. Holding your finger down on an element and waiting for it to lose focus after a while does not fire any events, even though a case could be made for firing the mousedown event as soon as the user’s finger touches the screen.

When the mouse is moved.

Yes Yes Yes Alternative Yes Yes Yes
  • On the iPhone a mousemove event is equivalent to a mouseover event. It fires on an element when the user focus moves to that element.

When the mouse leaves an element.

Yes Yes Yes Alternative Yes Yes Yes
  • On the iPhone these events fire when the user focus moves from one element to another. When an element gains the focus it fires mouseover, when it loses the focus it fires mouseout.

When the mouse enters an element.

Yes Yes Yes Alternative Yes Yes Yes
  • On the iPhone these events fire when the user focus moves from one element to another. When an element gains the focus it fires mouseover, when it loses the focus it fires mouseout.

When the user releases a mouse button.

Yes Yes Yes Yes Yes Yes
  • The iPhone fires the mousedown, mouseup and click events in the correct order on a click (tap), but it either fires all three or none at all. See mousedown.
Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7

When the user uses the mousewheel. Note that the page does not have to scroll for the event to fire.

No Yes Buggy No Yes Alternative Yes Yes No

It is possible to cancel the default action so that the element does not scroll.

  • If a mousewheel event handler is defined on an element in IE8rc1, using the mouse wheel does not scroll the element. The event fires correctly, though.
  • On iPhone, the mousewheel event fires only when the user scrolls a scrollable element (with overflow: auto), and not when he scrolls the document. (Scrolling a scrollable element is done with two fingers; not one.)

When text is pasted.

Yes No Buggy Yes Untestable Yes No No
  • Firefox 3 has a lazy implementation.

When the user resets a form.

Yes Yes Yes Yes Yes Yes

When the window is resized.

Yes Yes Yes Buggy Yes Yes Yes
  • Safari iPhone is unpredictable. (I hoped it’d fire the event when the user zoomed in or out, but no such luck. On the other hand, the scroll event does fire in that situation.)
Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7

When something is scrolled.

Yes Yes Buggy Yes Buggy Yes No
  • Safari probably monitors scrollTop access in order to determine whether the user has scrolled an element with overflow: auto. (Not applicable to iPhone.)
  • Safari iPhone also fires this event when the user zooms in or out.

When the user selects text in a text input field.

Yes Yes Yes Untestable Yes Yes No

As far as I’m concerned this event should also fire when the user selects text in any element. No browser agrees, though.

When the user submits a form.

Yes Yes Yes Yes Yes Yes
Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
See also the key to my compatibility tables.

W3C events

The events below do not work with traditional event registration. You have to use addEventListener in order to capture these events.

I don’t understand why this should be so; it breaks the ancient and reliable rule that any event is available in any registration model.

The camelcase-like event names are required. Here, too, an old rule is broken: all other event names are strictly lower case.

Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
DOMActivate

Should fire when an element is activated.

Test page.

No Yes Incorrect and incomplete No Incorrect

A link is activated when the user follows it. A checkbox or radio is activated when it is checked or unchecked.

  • Safari, Chrome and Konqueror incorrectly treat this event as an equivalent of the click event. For instance, when you click on a text input or even on the document in general the event fires. It shouldn’t: clicking on a text input does not activate the text box. Firefox correctly fires a click event only.
  • Safari and Chrome do not fire this event on radios and checkboxes.
DOMAttrModified

An attribute in the DOM tree of the element has been changed.

Test page.

No Yes No No Yes No
  • Firefox and Opera 9 also fire this event when you scroll a page, even though no DOM attribute is modified.
DOMCharacterDataModified

Text in the DOM tree of the element has been changed.

Test page.

No Incomplete Incomplete Yes Yes Incomplete Incomplete
  • Firefox, Safari 3.0, Opera and Konqueror do not fire the event when you change character data through innerHTML.
Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
DOMFocusIn

As focus, but bubbles.

Test page.

No No No Incomplete Almost Yes Yes
  • Safari doesn’t fire the event when you use the mouse to focus on links or elements with tabindex.
  • Chrome doesn’t fire the event when you use the mouse to focus on links.
DOMFocusOut

As blur, but bubbles.

Test page.

No No No Incomplete Almost Yes Yes
  • Safari doesn’t fire the event when you focus on links or elements with tabindex.
  • Chrome doesn’t fire the event when you focus on links.
DOMMouseScroll

When the user uses the mouse wheel.

Test page.

No Yes No Untestable No No No

Equivalent of mousewheel.

DOMNodeInserted

A new node has been inserted into the DOM tree of the element.

Test page.

No Yes Yes Yes Yes Incomplete

If you change an element’s innerHTML, browsers first fire a DOMNodeRemoved event for every child node of the element, and then a DOMNodeInserted event for every child node in the new version.

  • Konqueror does not fire these events when you use innerHTML.
Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
DOMNodeRemoved

A node has been removed from the DOM tree of the element.

Test page.

No Yes Too many Too many Yes Incomplete

If you change an element’s innerHTML, browsers first fire a DOMNodeRemoved event for every child node of the element, and then a DOMNodeInserted event for every child node in the new version.

  • Safari fires two events when you remove one node.
  • Firefox and Opera also fire this event when you change the node’s content by innerHTML. Safari doesn’t. This is probably caused by the innerHTML implementations, and it is not considered a bug.
  • Konqueror does not fire these events when you use innerHTML.
DOMSubtreeModified

The most generic event: something in the DOM tree of the element has changed.

Test page.

No No Yes Yes Yes No Yes
textInput

Equivalent of keypress.

Test page.

No No Yes Yes No No

This is a DOM event, despite the "DOM" bit missing in the name. Therefore it does not work with traditional event registration.

Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
See also the key to my compatibility tables.

Microsoft events

Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
activate

Despite the name this event is an equivalent of focusin.

Test page.

Yes No No No No No
beforecopy

Test page.

Yes No No Yes Untestable Yes No No

I do not understand the real purpose of these events. However, when the user calls up a context menu that contains cut, copy and paste actions, beforecut, beforecopy and beforepaste all fire.

beforecut

Test page.

Yes No No Yes Untestable Yes No No

See beforecopy.

beforepaste

Test page.

Yes No No Incomplete Untestable Incomplete No No

See beforecopy.

  • Safari 3.1 and Chrome do not fire this event before an actual paste action. It works fine on context menus.
Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
deactivate

Despite the name this event is an equivalent of focusout.

Test page.

Yes No No No No No
focusin

As focus, but bubbles.

Test page.

No Yes No No No No No

Not available on the window.

focusout

As blur, but bubbles.

Test page.

No Yes No No No No No

Not available on the window.

hashchange

When the hash value of the location changes.

Test page.

No Yes No No No No No

This event might be interesting for monitoring Back/Forward in Ajax interfaces.

Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
mouseenter

When the mouse enters an element, but it doesn’t bubble.

MUCH more useful than mouseover. Come on, Mozilla. Come on, Apple. Come on, Google. Come on, Opera. Come on, KDE.

Test page.

Yes No No No No No

The other browsers should implement these events as soon as possible.

(Yes, I know I’m shouting, but I’ve been saying this since 2003 and nobody has ever paid my message the least attention.)

Mouseover and mouseout also fire when the user mouses over or out of a child element of the element you registered the events on. Mouseenter and mouseleave don’t. Thus, they are the true equivalent of CSS :hover.

Once these events are supported by all browsers, creating dropdown menus will become a walk in the park. It’s Firefox’s, Safari’s and Opera’s fault that we still have to waste hours and hours on carefully distinguishing between important and unimportant mouseover and mouseout events. If we just had mouseenter and mouseleave, all our problems would be solved.

mouseleave

When the mouse leaves an element, but it doesn’t bubble.

MUCH more useful than mouseout.

Test page.

Yes No No No No No

See mouseenter remarks.

Event IE 5.5 IE 6 IE 7 IE8rc1 as IE7 IE8rc1 as IE8 FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
See also the key to my compatibility tables.

AND

출처: http://user.chollian.net/~spacekan/dhtml/content.htm


용어 정의 Go to DHTML

JavaScript와 DHTML에서 사용하는 용어의 개념을 설명하는 곳입니다.


element 는 페이지에 있는 각 택들을 가리킵니다. <body>, <div>, <A> 등을 말합니다.

attribute 는 element가 가지고 있는 것들입니다. element의 형식을 지정합니다.
<div id=D1 style="...">DIV 1<div> 또는 <A href="깡통.htm" target="휴지통">깡통</A> 에서 굵은 글자들이 attribute입니다.

object 는 JavaScript와 DHTML에서 사용하는 최상위의 존재입니다.
창을 가리키는 window, body를 가리키는 document, link, form, layer, all 등 페이지에 있는 모든 것들은 하나의 object입니다. 이 object는 계층이 있고 각자에 지정된 역활을 수행합니다. object에 지정되어 있는것은 property, method, event 입니다. (DOM 참조)

property 는 object가 가지고 있는 구성요소 입니다. window object가 가지고 있는 property로는 name, parent, history, innerHeight , self, status 등등 object가 이들의 property를 가지고 object 자신의 역활을 합니다. property는 object가 가지고 있는 것들입니다. 또 CSS style에 지정한 것들도 W3C에서 property라고 부릅니다. <div style="color:red; font-size:15pt;"> 에서 굵은 글자들이 style property입니다.

method 는 object가 어떤 동작을 할 때 사용합니다. window의 method는 open(), alert(), close(), scroll(), setTimeout()등을 가지고 있습니다. 각 object에 지정된 method로 그 object를 사용할 수 있습니다. 우리말로 함수라고 말합니다.

event 는 사용자나 script(JavaScript, JScript 등)로 어떤 동작을 했을 때 일어납니다. 각 object에는 그 일어난 동작을 수용할 수 있는 event 종류가 지정되어 있습니다. 링크(<A..)의 event로는 mouseover, mouseout, click, mousedown, mouseup, dblclick 가 있습니다. 링크를 마우스로 누르면 click 이벤트가 일어납니다.

event handler 는 object의 property는 아닙니다. 단지, event 를 다룰때 사용하는 형식의 이름입니다. 링크에서 click 이벤트를 다루고자 한다면 <a href="abc.htm" onClick="JavaScript Code">abc</a> 처럼 onClick로 click이벤트를 지정하는 것입니다. 이것은 JavaScript 구문이 아니기 때문에 대소문자는 구분하지 않습니다. onClick나 OnClick, onclick 모두 사용할 수 있습니다 . property가 아니고 attribute입니다.


TOP           Go to UP            TOP
AND

출처: http://loser.miniwini.com/wp/archives/611


body { font-family: 폰트이름; font-size: 폰트크기; } 이라 지정해도 textarea, input 은 Firefox 에서 폰트 스타일이 안먹고 따로 논다. 이 현상은 body * { font-family: 폰트이름; font-size: 폰트크기; } 를 사용하여 해결할 수 있다. 그런데 이것이 버그인지, 내가 이해하기 어려운 약간 이상한 표준인지는 정확히 모르겠다.

===> 답변

파이어폭스의 문제가 아니구요. 원래 body의 글꼴 크기와 상관없는 거랍니다.

body의 글꼴 크기를 상속받지 않는 html 요소는 h1~h6, table, input, textarea 등이 있답니다.

body의 글꼴 크기를 상속받는 html 요소는 p, li 정도랄까요?



AND

출처: http://perfdrug.tistory.com/76

자바스크립트나 엘리멘트의 style의 속성을 사용해서 스타일 프로퍼티를 설정하지 않으면 자바스크립트에서 그 스타일 값을 가져올 수 없다. 가져올 수 있는 방밥은 다음과 같은 방법이 있다. getComputedStyel(IE용) 과 currentStyle(파이어폭스용) 을 이용하면 가져 올 수 있다.

예제는 아래와 같다.



<!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>Insert title here</title>

<style type="text/css">
#div1 {background-color: #ff0 }
</style>

<script type="text/javascript">
document.onclick = changeElement;

function getStyle(obj, jsprop, cssprop) {
        if (obj.currentStyle) {
                return obj.currentStyle[jsprop];

        } else if (window.getComputedStyle) {
                return document.defaultView.getComputedStyle(obj, null).getPropertyValue(cssprop);

        } else {
                return null;
        }
}

function changeElement() {
        var obj = document.getElementById("div1");
        alert(obj.style.backgroundColor);
        alert(getStyle(obj, "backgroundColor", "background-color"));

        obj.style.backgroundColor = "#ff0000";
        alert(getStyle(obj, "backgroundColor", "background-color"));

        alert(obj.style.backgroundColor);
}
</script>
</head>
<body>
        <div id="div1">
                <p>This is a DIV element</p>
        </div>
</body>
</html>
 



AND

출처: http://hanjava.net/call-151/2006/07/23/javascript%EC%97%90%EC%84%9C-%EC%99%B8%EB%B6%80-js-%ED%99%94%EC%9D%BC-import%ED%95%98%EA%B8%B0/

JavaScript는 import 기능이 없다.

따라서 common.js가 다음과 같고

JAVASCRIPT:
  1. function sum(x, y) {
  2.     return x+y;
  3. }

use.js가 아래와 같다면

JAVASCRIPT:
  1. function useSum() {
  2.     alert( sum(10, 20) );
  3. }

HTML 화일에서는 src속성을 포함한 script tag를 두번 사용해야 한다. 그리고 실제로 useSum()을 실제로 호출해 사용하는 script tag가 하나 더 필요하다.

그런데 use.js는 원래 common.js에 depedency가 있는것이기 때문에 두번 import하기가 불편하다.
이럴땐 use.js에 다음 한줄을 추가한다.

JAVASCRIPT:
  1. document.write("<script src='common.js'></script>");
  2. function useSum() {
  3.     alert( sum(10, 20) );
  4. }


 
AND

출처: http://junho85.tistory.com/tag/JavaScript
개발이야기/JavaScript 2008/02/19 13:12
일단 결론 부터 말하자면 아래의 함수이다.
  1. function addEvent(obj, type, fn)   
  2. {   
  3.     if (obj.addEventListener)   
  4.         obj.addEventListener(type, fn, false);   
  5.     else if (obj.attachEvent)   
  6.     {   
  7.         obj["e"+type+fn] = fn;   
  8.         obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }   
  9.         obj.attachEvent("on"+type, obj[type+fn]);   
  10.     }   
  11. }  

익스플로러에 대한 처리가 이전에 봤던 이벤트 처리랑 좀 다른게 있는데 정확한 이유는 모르겠다.

참고자료는 CDK Standard Magazine Forum 글을 참고했다.
http://forum.standardmag.org/viewtopic.php?id=1250

어찌 되었건 표준은 addEventListener 인데 IE에서는 attachEvent를 쓴다.
그래서 브라우저간 호환성 때문에 이러한 처리가 필요해진다. (아마 IE가 점유율이 높지 않았다면 IE가 패치를 해서 바꿔야 했겠지.)

그리고 IE에서는 이벤트를 붙일때 on을 넣어 주어야 한다. 나도 on이 익숙해져 있었는데 표준에서는 on이 없단다.

ps.
onload와 onLoad삽질 경험담...
X : addEvent(window, "load", onload); // onload 소문자로만 이루어진 onload 사용 불가
O : addEvent(window, "load", onLoad);


이상하게도 onload함수를 선언해서 사용해서 이벤트를 붙여서 쓰게 되니 정상적으로 동작하지 않는 경우가 발생하였다.
이런저런 이유가 있을듯 한데 참고 하기 바람



네이버 블로그에 올렸던 내용을 옮겨 오며 일부 수정 하였음
http://blog.naver.com/jworld2000/70027615982


AND

출처: http://cafe.naver.com/webmajjang.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=11

getElementById와 getElementsByName의 차이는


단일값이냐? 아니면 배열값이냐? 라는 차이로 보면 쉬울듯.

 

<input id="one" value="ㅋㅋ">


의 값을 알고자 한다면 스크립트로..


var Obj = document.getElementById("one");

alert( Obj.value );// ㅋㅋ 가 출력됨

 

그럼 getElementsByName의 예는,


<input name="test" value="일번">
<input name="test" value="2번">
<input name="test" value="Three">


<script language="javascript">
   var obj = document.getElementsByName("test");
   alert(obj[0].value); // 일번이  출력됨
   alert(obj[1].value); // 2번이 출력된
   alert(obj[2].value); // Three가 출력됨
</script>

AND

출처 : http://blog.naver.com/sjs1022?Redirect=Log&logNo=60041130549

◆ 자바스크립트 기초

◎ <꼭 알아두어야 할 것 >
------------------------------------------------------------------------------------------------------
▶ 문법에 맞지 않는 글자가 단 한자라도 있거나 구절이 있다면 스크립트 실행 시 에러가 납니다.
▶  <script language="javascript">로 시작하여 </script> 로 닫아줍니다.
이 것은 language="javascript" 명령으로 사용된 스크립트가 자바스크립트임을 알려주는 것으로 <script>태그를 생략하면 자바스크립트는 실행되지 않고 일반텍스트로 간주하여 본문에 스크립트 소스가 그대로 표시됩니다.
-----------------------------------------------------------------------------------------

◎ HTML 문서안에서 자바스크립트의 기본 구조

<HTML>
<HEAD>
<TITLE>자바스크립트 소스의 기본 구조 </TITLE>
<SCRIPT language="JavaScript">
<!--
/* 이 안에는 프로그램을 설명하고 나중에
분석하기 쉽도록 필요한 주석문을 기입합니다.*/
function test()   //test() 라는 함수를 정의
{
 실행될 함수의 내용  //한줄짜리 주석문
}
//-->
</SCRIPT>
<NOSCRIPT>
자바스크립트를 지원하지 않는 브라우저에 나타날 내용
</NOSCRIPT>

</HEAD>
<BODY>
<!--   아래와 같이 바디태그 안에 실행부분을 기록하는데 클릭이라 적혀있는 버튼을 클릭 시 헤드 부분에서 정의한 함수 test() 를 실행하는 예   -->
<input type="button" value="클릭" onClick="test();">
</BODY>
</HTML>


● 위 내용에 대한 분석
▶ 생략기호 <!--    -->
는 자바스크립트를 지원하지 않는 브라우저에서 스크립트의 실행을 하지 못하게 합니다.
이 유는 실행오류나 문서의 깨짐을 방지하기 위함입니다. 대부분 웹브라우저에서 자바스크립트를 지원하므로 생략기호를 사용하지 않아도 되지만 핸드폰이나 PDA 등의 브라우저에서는 비교적 간단한 검색만 지원하고 자바스크립트를 지원하지 않으므로 이러한 브라우저를 생각한다면 생략기호로서 실행을 막아야 합니다.
▶ 여러 줄 주석문 : /*주석내용*/ , 한줄 주석문 : // 
주석이란 문서 제작자가 소스를 분석하기 쉽게 필요한 곳에 기록해 놓는글로서 프로그램에는 지장을 주지 않고 화면에 나타나지도 않습니다.
html에서의 주석문은 <!-- 주석문 -->  을 사용합니다. 만일 html 태그 안에서 위 자바스크립트 주석문을 사용하면 주석문의 효력이 없고 텍스트 그대로 화면에 나타나게 됩니다.
한줄짜리 주석문 기호 // 에 비해 여러 줄을 기록할 수 있는 주석기호 /* 는 꼭 주석이 끝나는 줄에서 */ 로 닫아주어야 합니다.

▶ <NOSCRIPT>내용</NOSCRIPT>

태그는 자바스크립트를 지원하지 않는 브라우저를 위한 태그입니다.
이 태그로 둘러싸인 문장이나 태그는 자바스크립트를 지원하지 않는 브라우저에서 자바스크립트 프로그램 실행 대신 화면에 나타나게 됩니다.
자바스크립트를 지원하는 브라우저에서는 화면에 나타나지 않고 아무런 작용도 하지 않습니다.

◎<SCRIPT  language="JavaScript>
에서 language 속성은 스크립트의 종류와 버전을 웹브라우저에 알려주는 속성인데 대부분 웹브라우저의 기본 스크립트는 자바스크립트이므로, <SCRIPT>태그만 사용해도 됩니다.
하지만 그렇지 않은 브라우저도 있기 때문에 <SCRIPT language="JavaScript"> 로 시작하는 것이 좋습니다.

◆ JavaScript 작성 예제 1 ( test1.htm )
<HEAD>
<TITLE>자바스크립트 예제</TITLE>
<SCRIPT language="JavaScript">
<!--
function test()
{
 alert("안녕하세요? 이 창을 경고창, 혹은 글월상자라고도 합니다.")
}
//-->
</SCRIPT>

<NOSCRIPT>
자바스크립트를 지원하지 않는 브라우저에 나타날 내용<br>
<img src="http://218.234.208.9/o.jpg">
</NOSCRIPT>

</HEAD>
<BODY onLoad="test();">
</BODY>
</HTML>
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
◆ JavaScript 작성예제 2 ( test2.htm )
<HTML>
<HEAD>
<TITLE> 홍길동의 홈페이지 </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
   document.write("<HR>");
   document.write("안녕하세요.. 홍길동입니다.");
   document.write("<HR>");
</SCRIPT>
</BODY>
</HTML>
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
◆ JavaScript 작성예제 3 ( test3.htm )
<HTML>
<HEAD>
<TITLE> 홍길동의 홈페이지 </TITLE>
</HEAD>
<BODY>
<SCRIPT SRC=test3.js>
</SCRIPT>
</BODY>
</HTML>

◇ test3.js
   document.write("<HR>");
   document.write("안녕하세요.. 홍길동입니다.");
   document.write("<HR>");

JavaScript 코드를 HTML 문서와 별도로 작성하는 경우, JavaScript 파일은 확장자 이름을 “.js”로 저장해야 하고, 이문서는 <SCRIPT> 태그를 사용하지 않는다.

┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
◆ JavaScript 작성예제 4 ( test4.htm )
<HTML>
<HEAD>
<TITLE> 홍길동의 홈페이지 </TITLE>
</HEAD>
<BODY onLoad="document.write('안녕하세요.. 홍길동입니다.');document.write('<HR>');">
</SCRIPT>
</BODY>
</HTML>
JavaScript를 작성하는 또 다른 방법은 HTML 태그 안에 옵션 값으로 작성하는 방법이다. 이는 이벤트에 의해 동작하는 방법으로 다음과 같이 작성한다.
<HTML_태그  이벤트명 = “JavaScript_Code">
※document.write 명령문은 웹브라우저에 지정한 문자열을 출력하라는 명령이다. document객체에서 설명한다.


◆ 변수와 상수의 이해
변수란 단어가 뜻하는 바 그대로 변하는 수라는 것을 의미하고, 상수란 항상 변하지 않는 수라는 것을 의미합니다. 사용자가 프롬프트 입력창에 입력한 데이타를 화면에 출력해주는 간단한 예를 들어 이해를 해 봅니다.
<HTML>
<HEAD>
<TITLE>변수,상수의 이해</TITLE>
<script language="javascript">
<!--
var a=prompt("사랑하는 이의 이름을 입력하세요","");
document.write("당신이 사랑하는 사람은 "+a+" 입니다.")
//-->
</script>
</HEAD>
<BODY>
</BODY>
</HTML>

위에서
var a=prompt("사랑하는 이의 이름을 입력하세요",""); 은
프롬프트 입력창을 띄워서 사용자가 입력한 내용을 a 라는 변수에 대입하고,
document.write("당신이 사랑하는 사람은 "+a+" 입니다.") 은
문장과 변수 a의 값을 화면에 출력해 줍니다.

즉, a 는 사용자가 입력한 내용에 따라 수시로 변하게 되므로 변수 가 되는 것입니다.
변수는 위에서 알수 있듯이 var 로 선언을 합니다.
물론 var 는 생략할 수도 있으나 기본적으로 변수를 뜻하는 variable 의 약자인 var 로 선언을 하는 것입니다.

변수의 반대되는 개념은 상수인데, 상수는 항상 변하지 않는 수로서 숫자 1 이나 2와 같은 숫자나 문자가 이에 해당합니다.
숫자 1 은 1로서 2나 3이 될 수 없기 때문에 상수가 되는 것입니다.

┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
◆ 변수의 선언과 정의
변수는 선언을 함으로서 프로그램에 그 변수가 사용될 것임을 미리 알리고, 선언된 변수에 어떤 값을 대입하는 것을 정의(초기화) 한다고 합니다. 변수를 정의한다는 말을 “대입한다” 또는 “초기화한다”라고도 합니다.

아래는 변수를 선언할 때 알아두어야 할 몇 가지입니다.
1. 변수를 선언할 때 var명령을 사용하는데 var는 생략을 해도 됩니다. 하지만 var가 대문자가 되어서는 안됩니다.
2. 변수 이름은 대, 소문자를 정확히 구별함으로 주의합니다.
3. 변수를 여러개 선언할때는 ,(쉼표) 로 구분하여 선언합니다.
4. 함수 안에 변수를 사용할 때는 따옴표를 사용하지 않습니다.
5. 변수는 선언을 함과 동시에 정의를 할 수 있습니다.
다음은 위의 주의사항을 참고하여 일례로 z 라는 변수를 선언함에 있어서 맞는 예입니다.
z;    //var 명령을 생략하였을 경우
var z;   //var 명령을 사용하였을 경우
var z,x,y;   //쉼표로 z,x,y 라는 세 개의 변수를 동시에 선언할 경우
var z=0;  //z 라는 변수를 선언함과 동시에 0 이란 값을 변수 z 에 대입(정의, 초기화)한 경우
var z=0,x=1,y=2;  //변수z에는0, 변수x에는1, 변수y에는2 라는 값을 변수 선언과 동시에 대입한 경우
아래는 틀린 예입니다.
varz;   //var 명령과 z 변수 이름이 붙어 있으므로 틀린 예입니다. var 와는 한 칸 띄워야 합니다.
VAR z; //var 명령은 소문자로 하여야 하므로 틀린 예입니다.
var zxy;  //여러개의 변수를 선언할 경우 쉼표로 구분해야 하므로 틀린 예입니다.

◇ 변수 작성 규칙
㉠ 변수를 사용하기 전에 반드시 변수를 선언해야 합니다.
㉡ variable 의 약자인 var로 변수를 선언을 알리고 ; 기호로 닫습니다.
㉢ 변수이름은 영문 혹은, “_”로 시작해야 합니다.(한글, 특수문자는 변수이름으로 사용불가)
㉣ 함수 이름이나 예약어는 변수의 이름으로 사용할 수 없습니다. (this, var, true, null, if, for...)
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
◆ 자바스크립트의 자료형
◇ 정수형 자료
정수형 자료는 숫자 0,1,2 혹은 -3 과 같이 소수점이 붙지 않은 정수형입니다.
자바스크립트에서 정수형 숫자를 표시할 때는 10진수와 16진수 방식을 사용합니다.
우리가 흔히 사용하는 정수형 0,1,2,-3 과 같은 것이 10진수이고,16진수 방식은 숫자 앞에 0x 기호를 붙입니다.
예를 들면 16진수 0x7 은 10진수 7이 되고, 16진수 0x10 은 10진수 16이 된다.

<HTML>
<BODY>
<script>
<!--
 var a = 7
 var b = 0x7
 alert("a 는 " + a + "이고, b는 " + b +"입니다.")
//-->
</script>
</BODY>
</HTML>
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
◇ 실수형 자료
실수형은 3.14 와 같이 소수점이 들어간 것입니다.
또, 실수형은 가수부와 지수부로 표현할 수 있기 때문에 정수형 보다 큰 수를 다룰 수가 있습니다.
예를 들어 1억 이란 수를 표현할 때 10진수로 표시하려면 9자리의 자리수가 필요합니다.
하지만 이것을 가수부와 지수부로 표기하면 108 이 됩니다. 즉 가수부 10 과 지수부 8로 나누어서 표기할 수 있습니다. 이것을 다시 지수표기로 표기하면 1.0E8 이 됩니다.
1.0e8 과 같이 소문자로 해도 됩니다.

<HTML><BODY>
<script language="javascript">
<!--
 var a=1.0e8;
 var b=1.0E8;
 var c=1.23e2
 var d=3.5e-3;
 document.write("1.0e8 의 값은 "+a+" 이고<br>1.0E8 의 값은 "+b+" 이고")
 document.write("<br>1.23e2 의 값은 "+c+" 이고,<br>3.5e-3 의 값은 "+d+" 입니다.");
//-->
</script>
</BODY></HTML>
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
◇ 문자형 자료
문자형 자료는 가,나,다,A,B,C 와 같은 문자를 표현하기 위한 자료입니다.
숫자도 문자형 자료가 될 수 있지만 이때는 큰따옴표 또는, 작은 따옴표로 묶어 주어야 합니다.
즉, 문자를 표시하기 위해서는 큰따옴표와 작은 따옴표로 묶어주어야 합니다.
<HTML><BODY>
<script language="javascript">
<!--
 var a="소스나라";
 var b="1+2"//변수 c 의 값은 숫자이지만 따옴표로 묶었기에 문자열이 됩니다.
 var c=1+2; //변수 c 의 값은 따옴표로 묶지 않았기에 계산식이 됩니다.
 document.write("a 의 값은 "+a+" 입니다.<br>");
 document.write("b 의 값은 "+b+" 입니다.<br>");
 document.write("c 의 값은 "+c+" 입니다.<br>");
//-->
</script>
</BODY></HTML>
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
◇ 논리형 자료
논리(boolean)형 자료는 논리를 판단하여 참(true)와 거짓(false)값을 표기해 줍니다.
논리형 자료인 true 와 false 는 문자형 자료가 아니므로 문자형 처럼  따옴표로 묶지 않습니다.
<HTML><BODY>
<script language="javascript">
<!--
var a=1;//변수 a 에 1을 대입
var b=2;//변수 b 에 2를 대입
var c=(a<b);
var d=(a>b);
document.write("c 의 값은 "+c+" 입니다.<br>");
document.write("d 의 값은 "+d+" 입니다.<br>");
//-->

</script>
</BODY>
</HTML>

AND

출처: http://blog.naver.com/i74080?Redirect=Log&logNo=60044578874

typeof 연산자

식의 데이터 형식을 나타내는 문자열을 반환합니다.

typeof[(]expression[)] ;

expression 인수는 형식 정보를 찾는 임의의 입니다.

참고

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

선택적인 요소로 typeof 구문에 괄호를 사용할 수도 있습니다.


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

{

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

}


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


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

{

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

}





다른 방식...


다음 함수는 사이먼 윌리슨(http://simonwillison.net/)이 만들었습니다. 이 함수는 문서의 로딩이 완료되었을 때 실행되어야 하는 함수에 대한 참조를 인자로 받습니다.

     형식 :  addLoadEvent(함수명);

     ex)      addLoadEvent(prepareLinks);


function addLoadEvent(func) {

    var oldonload = window.onload;

    if (typeof window.onload != "function") {

        window.onload = func;

    } else {

        window.onload = function() {

            if(oldonload){

                oldonload();

            }

            func();

        }

    }

}


AND

AND