'분류 전체보기'에 해당되는 글 87건

  1. 2021.07.29 ---20 자바스크립트 객체, 속성, 메소드 이해하기
  2. 2021.07.29 ---20 객체와 배열이란?
  3. 2021.07.20 30 Ajax 함수 상세 설명
  4. 2021.07.20 10 readonly, disabled 컨트롤
  5. 2021.07.20 10 $("tr[seq] a[href]").click(function() { 사용법
  6. 2021.07.20 20 textarea에서 2줄띄어쓰기시에 jquery로 innerHTML하면 오류 해결방안
  7. 2021.07.20 10 <li>list item 1</li>에서 $('li').eq(2).css('background-color', 'red');
  8. 2021.07.16 30 parseInt 와 Number비교
  9. 2021.07.16 30 대소문자전환 toUpperCase() toLowerCase()
  10. 2021.07.16 30 replace 문제점
  11. 2021.07.16 31 날자관련 각종 utils
  12. 2021.07.16 31 날자관련 두 날자사이에 시간을 계산한다
  13. 2021.07.16 31 날자관련 날자계산
  14. 2021.07.16 11 switch case문 1
  15. 2021.07.15 객체의 활용 (객체내에 생성자, 변수(메소드)추가 삭제(delete))
  16. 2021.07.15 10 객체 생성 및 접근 (for , in , with사용)
  17. 2021.07.15 인코더(Encoder), Eval함수 ,숫자변환함수
  18. 2021.07.15 10 Function(함수)
  19. 2021.07.15 10 제어문(if 문 , for 문)
  20. 2021.07.15 10 변수의 선언
  21. 2021.07.15 10 출력문(document.write // Console.log //alert)
  22. 2021.07.15 10 Java Script 개요와 개발환경설정
  23. 2021.07.15 ---10 배열 선언및 출력
  24. 2018.07.18 31 날자관련 var d = new Date();
  25. 2013.01.18 30 substring과 substr의 차이
  26. 2013.01.11 <body onload=""> 그리고 window.onload와 window::onload()의 차이
  27. 2011.12.25 30 타이머함수 setInterval(), setTimeOut(), clearInterval()

1) 객체(Objet)
우리가 일상 생활에서 접하는 유형 무형의 모든 것이 객체라고 할 수 있습니다. 사람, 컴퓨터, 시계와 같이 눈에 보이는 것 뿐 만 아니라 마음과 같이 보이지 않는 것도 객체의 자격이 있습니다. 자바스크립트에서 객체는 일반적으로 웹브라우저와 관계되어 사용됩니다. 즉 브라우저 윈도우, 웹문서, 문서에 포함된 이미지, 폼 등과 같은 요소들이 하나의 객체가 됩니다. 이외에도 시간, 배열 등과 같이 자바스크립트 자체에 내장된 객체도 있으며 사용자가 정의한 객체도 사용할 수 있습니다.

2) 속성(Property)
자바스크립트에서 각각의 객체들은 속성을 가집니다. 사람이라는 객체의 속성인 얼굴은 눈, 귀, 코와 같은 속성을 가진 또 다른 하나의 객체가 될 수 있습니다.. 즉 하위 객체는 상위 객체의 속성이 됩니다. 자바스크립트에서도 이미지는 분명 하나의 객체이지만 document 객체의 속성이 되기도 합니다. 웹 문서는 자바스크립트에서 객체이고 배경색, 문서의 제목 등과 같은 속성을, 이미지는 너비, 높이 등의 속성을 가집니다. 객체의 속성을 바꾸기 위해서는 도트(.)를 사용하여 다름과 같이 구분해 적어주면 됩니다.

ex) 객체,속성 = "속성값"

예를 들어 웹문서의 배경색을 검은색으로 바꿀려면 어떻게 해야 할까요? 웹문서는 'document'이라는 객체이고 배경색은 bgcolor라는 속성명으로 표현되므로 다음과 같이 압력하면됩니다.

ex) documnet.bgcolor="black"

3) 메소드(Method)
속성이 객체에 속한 성질이라면 메소드는 객체의 동작을 좌우하는 것입니다. 사람을 웃게 한다든지 컴퓨터를 켜게 하는 것과 같이 어던 행동과 동작을 유발하는 것이 바로 메소드의 역활입니다.

자바스크립트에서는 'open( ) 메소드'를 이용하여 새로운 창을 열수도 있고(), 'write()메소드'를 이용하여 웹문서에 문자열을 출력한느 등 갖가지 흥미로운 효과를 가져 올 수 있습니다.

ex) 객체, 메소드(값)

Posted by useways
,

원문: https://inhaeng.tistory.com/10

객체(Object)

 

객체란, 현실의 사물을 프로그래밍에 반영한 거다. 코드로 보는 게 이해하기 쉽겠지? 

나를 프로그리맹에 반영해서 간단한 코드로 만들어보자!

 

바로 이게 나를 자바스크립트로 구현한 것이다. 위와 같이 heo라는 변수에 { }로 감싼 덩어리를 넣었다.

바로 이 덩어리가 나를 표현하는 객체이다. 객체의 부분별 이름을 살펴보자!

 

속성(Property)

 

객체 안을 보면 firstName과 lastName이 왼쪽에 있고, 'inhaeng'과 'Heo'가 오른쪽에 있다.

콤마로 구분되는 것들을 객체의 속성이라고 부른다. heo 객체에는 firstName: 'inhaeng'과 lastName:'Heo'까지 두 개의 속성이 있다.

속성끼리는 쉼표로 구분해준다. 위에서는 보기 좋게 줄 바꿈을 했지만, 꼭 줄바꿈을 해야 하는 것은 아니다. 

var heo = { firstName: 'inhaeng', lastName:'Heo'}; 처럼 쉼표로 구분되기만 하면 충분하다.

 

나를 heo라는 객체로 표현했다고 했는데 너무 간단한게 마음에 들지 않는다면 age, height, weight 등 여러가지 속성을 더 추가할 수 있다. 자신을 직접 객체로 표현해보자!

 

키(key)와 값(value)

 

속성에서 firstName과 lastName같은 것들을 객체의 키라고 부르고 'inhaneg'과 'Heo'를 값이라고 부른다.

(괄호 안의 영어는 외워두는게 좋다.) 즉, 속성은 키:값의 관계로 이루어져있다. 키는 속 성명이라고 생각하면 된다.

 

참고로 키는 문자열만 가능하다. 또 한가지, 속성명은 따옴표가 없어도 된다. 있어도 상관은 없다. 위를 보면 firstName과 lastName은 문자열인데도 따옴표로 안 감싸줬다. 반드시 따옴표로 감싸줘야 하는 경우도 있다. 바로 키에 띄어쓰기가 들어간 경우이다.

 

var wrap = { 'ex ample': 'wrap' };

위와 같은 경우, wrap 객체의 속성명은 'ex ample'이다. 이렇게 속성명 안에 띄어쓰기가 들어있을 경우는 따옴표로 감싸준다.

 

속성 값은 어떤 값이든지 상관없다. 문자열이어도 되고, 숫자여도 되고, 객체여도 된다. 아직 안 배웠지만, 객체나 함수여도 상관없다.

미리 말하자면 속성 값이 함수인 것을 우리는 메서드라고 특별히 따로 부른다.

 

그렇다면 heo 객체 안에 firstName이나 lastName 속성의 값을 사용하고 싶을 땐 어떻게 할까?

아까 키가 속성의 이름이라고 했다. 객체한테도 속성의 이름을 부르면 된다!

 

이렇게 접근할 수 있다. 마침표를 사용해서 heo 객체 안의 속성들에 접근하는 거다. 

아니면 [] 안에 속성명을 적어서 접근할 수도 있다. 하지만 [] 안에 적는 것보다는 주로 마침표를 사용한다. 어쩔 수 없이 [] 안에 적어야 하는 경우는 위에서처럼 속성명에 띄어쓰기가 들어가 있는 경우이다. 아까 wrap 객체 안의 'ex ample' 속성에 접근하고 싶을 때는 wrap['ex ample'] 이렇게 접근해야 한다. 그냥 wrap[ex ample]하면 오류가 난다.

 

객체를 다양하게 활용하는 방법을 살펴보자

 

위와 같이 객체 안의 속성을 바꿀 수도 있다.

 

아까도 말했듯이 객체 안에 속성값으로 객체가 들어갈 수도 있다. heo 객체의 속성으로 body가 있는데 그 값이 다시 객체인 거다. 객체의 속성에 접근하는 것이니까 마침표를 사용해서 점점 더 안으로 들어가면 된다. 객체를 사용해서 복잡한 데이터 구조를 짤 수 있겠지?

 

객체의 속성을 삭제하는 방법도 있다. 앞에 delete 키워드를 붙이면 된다. 위의 예제와 이어진다.

 

 

객체 중에는 특수한 객체가 있다. 바로 함수(Function)와 배열(Array)이다.

 

배열(Array)

배열은 []로 감싸서 나타내고, 객체 리터럴처럼 안에는 무엇이든지 다 들어갈 수 있다. 배열 안에 배열이 들어가도 되고, 배열 안에 객체가 들어가도 된다. 아직 안 배웠지만 함수도 들어갈 수 있다. 배열 안에 들어간 것들을 우리는 요소(item)라고 부른다. 객체의 속성처럼 쉼표로 구분하면 된다. 

 

자바스크립트는 배열의 길이를 미리 정할 필요가 없다. 안의 요소에 따라 자동으로 늘어나거나 줄어든다.

 

객체와의 차이점은 키가 없다는 거다. 그냥 값들만 순서대로 나열되어 있다. 아까 heo객체를 생각해보자. 거기서 키만 없으면

이런 모양이 되는거다. 굳이 키가 필요하지 않고 값만 많이 나열하고 싶을 때 배열을 사용한다.

 

배열 안의 요소를 선택하려면 뒤에 몇 번째 요소인지 숫자를 붙여준다. 자바스크립트에서는 0이 첫 번째다. 따라서 [0]을 붙이면 첫 번째 요소 inhaeng가 선택되고, [1]을 붙이면 두 번째 요소 heo가 선택된다.

 

heo[0]; // 'inhaneg'

heo[1]; // 'heo'

 

사실 배열도 키가 있다. 배열은 자동으로 키가 0,1,2,3,... 순서로 주어진다. 즉 'inhaeng' 값의 키는 0이고, 'heo'값의 키는 1이다. 위에서 요소를 선택한 원리가 바로 이거다. 키를 통해 배열의 요소를 선택한 것이다.

아까 객체는 []안에 속성 이름을 넣어서 값을 불러오는 방법도 있다. 그와 비슷하다.

어떻게 보면 

 

하지만 위와 같은 방법보다는 그냥 [] 안에 넣는 것을 자주 사용한다. 그리고 []를 사용하는 게 권장사항이기도 하다.

new를 사용하지않고 []만 사용해서 만든 배열을 배열 리터럴이라고 부른다. 객체 리터럴 같은 거다.

 

객체와 배열은 특성상 대부분의 프로그래밍 언어에 있다. 이들은 나중에 배울 자료구조와 알고리즘의 기본이기도 하다.

 

마지막 객체로는 함수가 있다. 함수는 객체나 배열보다 더 중요하기 때문에 다음에 설명한다.

'12 Javascript > 10 기초부분' 카테고리의 다른 글

---10 자바스크립트의 객체 및 변수 개념잡기  (0) 2021.07.29
00 자바스크립트란?  (0) 2021.07.29
11 switch case문  (1) 2021.07.16
10 Function(함수)  (0) 2021.07.15
10 제어문(if 문 , for 문)  (0) 2021.07.15
Posted by useways
,

http://drst3in.webdoor.co.kr/tc/228

jQuery로 Ajax를 어떻게 쉽게 사용할 수 있는지 보도록 하겠습니다..

jQuery.ajax(settings)

$.ajax(settings)


기본 사용법은 이렇습니다.. 파라미터로 넘어가는 settings 안에서 모든것을 처리하면 됩니다.
settings에 사용되는 속성들을 한번 보겠습니다.

asyncBoolean
Default: true

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

beforeSend(XMLHttpRequest)Function

A pre-callback to modify the XMLHttpRequest object before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument. This is an Ajax Event. You may return false in function to cancel the request.

cacheBoolean
Default: true, false for dataType 'script' and 'jsonp'

If set to false it will force the pages that you request to not be cached by the browser.

complete(XMLHttpRequest, textStatus)Function

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string categorizing the status of the request ("success""notmodified""error","timeout", or "parsererror"). This is an Ajax Event.

contentTypeString
Default: 'application/x-www-form-urlencoded'

When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.

contextObject

This object will be made the context of all Ajax-related callbacks. For example specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

$.ajax({ url: "test.html", context: document.body, success: function(){
        $(this).addClass("done");
      }});

 

dataObject, String

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

dataFilter(data, type)Function

A function to be used to handle the raw responsed data of XMLHttpRequest.This is a pre-filtering function to sanitize the response.You should return the sanitized data.The function gets passed two arguments: The raw data returned from the server, and the 'dataType' parameter.

dataTypeString
Default: Intelligent Guess (xml, json, script, or html)

The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

  • "xml": Returns a XML document that can be processed via jQuery.
  • "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
  • "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.
  • "text": A plain text string.

 

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.

globalBoolean
Default: true

Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.

ifModifiedBoolean
Default: false

Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.

jsonpString

Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So{jsonp:'onJsonPLoad'} would result in 'onJsonPLoad=?' passed to the server.

jsonpCallbackString

Specify the callback function name for a jsonp request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests.

passwordString

A password to be used in response to an HTTP access authentication request.

processDataBoolean
Default: true

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

scriptCharsetString

Only for requests with "jsonp" or "script" dataType and "GET" type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.

success(data, textStatus, XMLHttpRequest)Function

A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the 'dataType' parameter; a string describing the status; and the XMLHttpRequest object (available as of jQuery 1.4). This is an Ajax Event.

timeoutNumber

Set a local timeout (in milliseconds) for the request. This will override the global timeout, if one is set via $.ajaxSetup. For example, you could use this property to give a single request a longer timeout than all other requests that you've set to time out in one second. See$.ajaxSetup() for global timeouts.

traditionalBoolean

Set this to true if you wish to use the traditional style of param serialization.

typeString
Default: 'GET'

The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

urlString
Default: The current page

A string containing the URL to which the request is sent.

usernameString

A username to be used in response to an HTTP access authentication request.

xhrFunction

Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

 

이것들이 파라미터 안에 사용될수 있는 속성들 입니다... 참 많습니다...

이걸 다 읽기 전에 사용법 보고 나서.. 차근 차근 보셔되 될것 같습니다... 예제 하나 보시죠..

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

 

이게 Ajax 코드 입니다.. 몇줄 되지도 않습니다... 쉽게 사용할 수 있죠?..

코드를 대충 보면.. $.ajax( 는 jQuery의 ajax함수를 사용하는 거고 {}로 쌓여있는 부분이 파라미터 들입니다.
기본적으로 두개를 사용하고 있습니다... 

url : 'ajax/test.html' 이 부분은.. ajax로 호출할 서버의 페이지 주소입니다.. 당연히 무언가를 받아오기 위해서 url를 호출해야 하겠죠... 

success : 이부분은 이벤트로.. 서버에서 결과를 정상적으로 받게되면... 이 이벤트가 호출이 됩니다.
이벤트이기 때문에 .. function(data)로 시작하죠... 그럼.. function(data) 에서 data는 서버에서 보내온 정보라 넘어오게 됩니다. 위의 예제에서는.. html 파일을 호출했으니 html 코드가 왔겠군요...

받은 정보를 $('.result')   class="result"인 엘리먼트의 innerHtml 로 바꾸는 코드입니다.

그럼.. 이벤트에(사이트에서는. .콜백함수라고 하고있습니다.) 어떤것들이 있는지 한번 보겠습니다.

  1. beforeSend is called before the request is sent, and is passed the XMLHttpRequestobject as a parameter.
  2. error is called if the request fails. It is passed the XMLHttpRequest, a string indicating the error type, and an exception object if applicable.
  3. dataFilter is called on success. It is passed the returned data and the value ofdataType, and must return the (possibly altered) data to pass on to success.
  4. success is called if the request succeeds. It is passed the returned data, a string containing the success code, and the XMLHttpRequest object.
  5. complete is called when the request finishes, whether in failure or success. It is passed the XMLHttpRequest object, as well as a string containing the success or error code.

 

5가지의 콜백 함수가 있군요...

beforeSend

는 서버로 요청을 보내기전 호출됩니다.

error

는 호출에 실패하였을때 호출됩니다.

dataFilter

는 ajax를 호출할때 파라미터로 dataType이라는것을 넘겨주게 되는데 이값을 검사하여 호출됩니다.

success

는 서버에서 데이터를 잘 받았을때 호출됩니다.

complate

는 성공이나 실패가나더라도.. 요청이 완료된 상태에서 호출이 됩니다.


dataType

그럼.. dataType이 뭔지 한번 볼까요?...
ajax가 서버로 정보를 요청하고 받을 결과가 어떤 데이터 포멧인지를 지정하는 변수입니다.

기본값을 xml 로 되어 있고 html, json, jsonp, script, text 를 사용할 수 있습니다.

text와 html은 결과 데이터를 그냥 통과시켜 버립니다. 많이 쓰게될 json은 json객체로 결과가 넘어오게 됩니다.
데이터를 배열접근하듯이 쉽게 접근할 수 있습니다.

data

data 속성은 서버로 보낼 post data를 지정하는 속성입니다. 제가 전전장에서 Form 가지고 놀기에서 설명했던 함수를 기억하시는 분이 있겠죠?... 호출하는 url 속성에 get 형식으로 데이터를 넘겨도 되지만.. 많은 데이터를 넘길때는.. data 속성을 사용해서 넣어주면.. post로 넘어가게 됩니다.
post 데이터는 항상 UTF-8로 인코딩 되어서 서버로 전달이 됩니다. data를 넘길때는.. 하나 설정해야 할 속성이 더 있습니다...

contentType 이라는 속성인데 이값을 application/x-www-form-urlencoded로 설정 해주어야 합니다.

기차 자세한 속성들의 정본 사이트를 참조하시면 됩니다... 

그럼.. 예제 를 한번 보겠습니다...

$.ajax({
   type: "GET",
   url: "test.js",
   dataType: "script"
 });

실행할 script 파일을 다운로드 받는 예제입니다.

$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

 

POST 형식으로 데이터를 넘겨서 서버에서 저장하고 메시지를 반환하는 예제입니다.

$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});


var html = $.ajax({
  url: "some.php",
  async: false
 }).responseText;


var xmlDocument = [create xml document];
 $.ajax({
   url: "page.php",
   processData: false,
   data: xmlDocument,
   success: handleResponse
 });
bodyContent = $.ajax({
      url: "script.php",
      global: false,
      type: "POST",
      data: ({id : this.getAttribute('id')}),
      dataType: "html",
      async:false,
      success: function(msg){
         alert(msg);
      }
   }
).responseText;


각 예제들은 사이트에서 확인 가능하며... 속성값들의 설명들을 다시한번 읽어보시기 바랍니다...



===>예제

<script>
function paging(){
    count++;
    
    $.ajax({
        type: 'post'
        , async: true
        , url: "/display.do?cmd=productListAppend&ordFlag="+'${ordFlag}'+"&categoryCd="+categoryCd+"&itemCode="+'${itemCode}'+"&count="+count
        , beforeSend: function() {
             $('#ajax_load_indicator').show().fadeIn('fast'); 
          }
        , success: function(data) {
            var response = data.trim();
            console.log("success forward : "+response);
            // 상품 리스트 할당
            $('#view_list').append(response);
            $('#product_count').html($('#view_list li.thumb').size());
          }
        , error: function(data, status, err) {
            console.log("error forward : "+data);
            alert('서버와의 통신이 실패했습니다.');
          }
        , complete: function() { 
            $('#ajax_load_indicator').fadeOut();
          }
    });
}
</script>

Posted by useways
,

Target text field:

type="text" id="target"/>

 

$("#control").toggle(

           function() {    

                     $('#target').attr("disabled", true);

           },

           function() {    

                     $('#target').removeAttr("disabled"); 

           }

);

 

Target text field:

type="text" id="target"> Disable target

 

$('#readonly').click(

           function() {    

                     if($('#readonly').attr("readonly") == true){

                                $('#readonly').val('');

                                $('#readonly').removeAttr("readonly");    

                     }

           }

);

 

[출처] http://blog.naver.com/findaday/117601025

 

http://blog.naver.com/PostView.nhn?blogId=affectionjs&logNo=140121650809

 

Posted by useways
,

 $("tr[seq] a[href]").click(function() {
             
             alert( $(this).attr("name") );

 

    "<tr height='30' seq='{0}' commentCnt='{4}' depth='{4}'  >" +
  "  <a href='#' name='{0}'>" +
  "  <td width='50'  align='center'> {1} &nbsp;</td>" +


===>위의 html에서 tr[seq] a[href] 의 조건이 선택하는 부분은 tr[seq] 부분이 아니라 a[href] 부분이라서
<a href='#' name='{0}'> 의 값을 가져온다.


===>alert( $(this).attr("name") ); 했을때 undefined 란 것이 나오면
 1. attr 속성에 name이 없는 경우
 2. name 있어도 xml에서 값이 정의 안된경우


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

alert( $("tr[seq] a[seq]").eq(5).attr("width") );    의미는 tr부분에 seq속성이 있어야한다.

Posted by useways
,


textarea에서 개행문자 및 줄띄어쓰기 처리


http://drst3in.webdoor.co.kr/tc/228

var review_contents = $.trim($('#Battlelink_review_write textarea[name="battlelink_review_contents"]').val().replace(/(\r\n|\n|\n\n)/gi,'[split]'));

review_contents=review_contents.replace(/\'/g,"''");
review_contents = review_contents.split("[split]")       

textarea에서 2줄띄어쓰기시에 jquery로 innerHTML하면 오류가 발생하는데

줄간격에서 생기는 문제여서 개고생하다가 처리방법을 찾았다....ㅡㅡ;;
Posted by useways
,

 

 <ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
  </ul>


$('li').eq(2).css('background-color', 'red');
위 스크립트를 실행하면 item 3 위치의 배경색이 빨간색으로 바뀌게 됩니다

만약 음수값을 인덱스로 사용하게 된다면 리스트의 뒤쪽부터 세어 나가면 됩니다. 아래 예제를 보시죠.
$('li').eq(-2).css('background-color', 'red');

 

Posted by useways
,


출처 http://smartjuho.tistory.com/40



자바스크립트에서 parseInt를 사용 시 주의사항입니다.

특히 자바를 사용하셨던 분은 더 혼동이 될 수도 있습니다. 

자바에서는 Integer.parseInt(String s)를 사용하여 문자를 숫자로 형 변환시 10진수로 변환이 됩니다.

하지만 자바스크립트에서는 무조건 10진수로 변경되지는 않습니다.

자바스크립트에서 parseInt('08')를 하시고 결과 값을 확인하시면 결과는 0이 나옵니다.

이유는 입력되는 문자열이 0으로 시작되었기 때문에 8진수로 변환이 되는 것 입니다.

당연히 8이겠지 하고 결과값을 예측하시고 코딩을 하셨다면 큰 낭패일 수 있습니다.

간단한 예로 
document.write(parseInt("010")+ "<br />"); //8진수 변환
document.write(parseInt("0x10")+ "<br />"); //16진수 변환
해결 방법은 간단합니다.
1번째 인수 다음 2번째 인수에 변환될 진수를 적어 주시면 됩니다.
document.write(parseInt("10",10)+ "<br />"); //10진수 변환
document.write(parseInt("10",8)+ "<br />"); //8진수 변환
document.write(parseInt("10",16)+ "<br />");  //16진수 변환



또는 Number("08")를 사용하시면 10진수로 변환됩니다.

parseInt로 게시판 검색해 봤는데 해당 내용이 없어서 올림니다.


가볍게 넘길수 있는지만 결과에 큰 오류를 가져올 수 있는 오류입니다.

Posted by useways
,


// 문자열을 대문자로 변환
s = s.toUpperCase();
document.write(s + '<br />');
// 출력 결과: ABC ABCD ADOBE PHOTOSHOP



// 문자열을 소문자로 변환
document.write(s.toLowerCase() + '<br />');
// 출력 결과: abc abcd adobe photoshop


===내가 사용하는 방법

<input name="b00_002" type="text" class="css_InputBox" style="ime-mode:inactive; width: 90px" value=""  onkeyup='keyToUpperCase(this);'>

영문자 입력을 받고  ime-mode:inactive;
대문자로 변환 onkeyup='keyToUpperCase(this);'  onkeyup 이벤트일때만 정상작동한다.


.js부분에

function keyToUpperCase(obj){   //영문을때만가능하다 한글로 입력되면 깨진다....
obj.value = obj.value.toUpperCase();
}

Posted by useways
,


function replaceAll(str,orgStr,repStr)
{
    return str.split(orgStr).join(repStr);



[JavaScript] 는 replace 함수 사용 시 한번 만 치환된다.
ex)
var a = "2008-08-28";
var b = a.replace("-","");
alert(b);

결과 값 : 200808-28

아래와 같이 split 함수와 join 함수를 쓰면 이러한 문제가 해결 된다.
ex)
var a = "2008-08-28";
var b = a.split("-").join("");
alert(b);

결과 값 : 20080828

Posted by useways
,

어디서 가져왔더라... 찾기 편하게....등록..

//===================================================================
// DateUtil
//===================================================================
// DateCmp(date1, date2)
// date_Format(ymd, formatmask)
// date_FormatYM(ym, formatmask)
// format_YYYYMM(object)
// format_YYYYMMDD(object)
// getCurrentTime()
// getDay()
// getDayInterval(time1,time2)
// getHour()
// getHourInterval(time1,time2)
// getMMDD( separator)
// getMonth()
// getMonthInterval(time1,time2)
// getRelativeTime(y,m,d,h)
// getYear()
// getYYYYMM( separator)
// getYYYYMMDD( separator)
// isDate(y,m,d)
// isDateYM(ym)
// isDateYMD(ymd)
// isDateYYYY(yyyy)
// isDateYYYYMM( yyyymm )
// isFormatDate(ymd, formatmask)
// isFormatDateYM(ym, formatmask)
// isFutureTime(time)
// isPastTime(time)
// isValidDay(yyyy, mm, dd)
// isValidHour(hh)
// isValidMin(mi)
// isValidMonth(mm)
// isValidTime(time)
// isValidTimeFormat(time)
// isYM(y,m)
// isYunNyun(y)
// shiftTime(time,y,m,d,h)
// toTimeObject(time)
// toTimeString(date)
// offMoneyFormat( obj ) 
// onMoneyFormat( obj )
// cala_day(year, month, day)
// cala_weekday( x_nMonth, x_nDay, x_nYear)
// day_display(x_nDayOfWeek)

/////////////////////////////////////////////////////
function isValidMonth(num) {
/////////////////////////////////////////////////////
//유효한(존재하는) 월(月)인지 체크
    if(num == "") return;
 try{
  //object.value = object.value.replace(/./gi,'');
  if(isNaN(num)) { 
   throw Exception;
  }
  var m = parseInt(num,10);
  if(! (m >= 1 && m <= 12)){
   throw Exception;
  }
  if(num.length == 1){
   num = "0"+num;
  }
 }catch(Exception){
  window.alert("월 입력 오류입니다.");
  num="";
  num.focus();
 }
}


/////////////////////////////////////////////////////
function isValidMonthCheck(num) {
/////////////////////////////////////////////////////
//입력된 문자열이 유효한 월(月)인지 체크, 여부리턴
    if(num == "" || num == null)
  return false;

 if(isNaN(num)) { 
  return false;
 }

 var m = parseInt(num,10);
 
 if(! (m >= 1 && m <= 12)) {
  return false;
 }

 return true;
}


/////////////////////////////////////////////////////
function isValidDay(yyyy, mm, dd) {
/////////////////////////////////////////////////////
//유효한(존재하는) 일(日)인지 체크
    var m = parseInt(mm,10) - 1;
    var d = parseInt(dd,10);

    var end = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    if ((yyyy % 4 == 0 && yyyy % 100 != 0) || yyyy % 400 == 0) {
        end[1] = 29;
    }

    return (d >= 1 && d <= end[m]);
}


/////////////////////////////////////////////////////
function getCurrentTime() {
/////////////////////////////////////////////////////
// 현재 시각을 Time 형식으로 리턴
    return toTimeString(new Date());
}

/////////////////////////////////////////////////////
function getYear() {
/////////////////////////////////////////////////////
// 현재 年을 YYYY형식으로 리턴
    return getCurrentTime().substr(0,4);
}

/////////////////////////////////////////////////////
function getMonth() {
/////////////////////////////////////////////////////
// 현재 月을 MM형식으로 리턴
    return getCurrentTime().substr(4,2);
}

/////////////////////////////////////////////////////
function getDay() {
/////////////////////////////////////////////////////
// 현재 日을 DD형식으로 리턴
    return getCurrentTime().substr(6,2);
}

/////////////////////////////////////////////////////
function getYYYYMM( separator) {
/////////////////////////////////////////////////////
// 현재 年月을 separator 로 구분하여 리턴
    return getYear() + separator + getMonth();
}


/////////////////////////////////////////////////////
function getMMDD( separator) {
/////////////////////////////////////////////////////
// 현재 月日을 separator 로 구분하여 리턴
    return getMonth() + separator + getDay();
}


/////////////////////////////////////////////////////
function getYYYYMMDD( separator) {
/////////////////////////////////////////////////////
// 현재 年月日을 separator 로 구분하여 리턴
    return getYear() + separator + getMonth() + separator + getDay();
}

/////////////////////////////////////////////////////
function getHour() {
/////////////////////////////////////////////////////
// 현재 時를 HH형식으로 리턴
    return getCurrentTime().substr(8,2);
}

/////////////////////////////////////////////////////
function format_YYYYMM(object) {
/////////////////////////////////////////////////////
/**
 * 연월(YYYYMM)의 유효성을 체크하고 표준 날짜 포맷 (YYYY/MM) 으로 변환하여 리턴
 * (주의 : 이 함수의 파라미터는 객체임 (input object))
 */
    var num, year, month;
    num=object.value;   
    while (num.search("/") != -1) { 
  num = num.replace("/","");
 }
 if (isNaN(num)) {        
     window.alert("숫자로만 작성하셔야 합니다.");
  object.focus();
  return "";
 }  
    if( num != 0 && (num.length >= 5 && num.length <= 6)) {
        year = num.substring(0,4);
        month = num.substring(4);
        if (isValidMonthYYYYMM(object, month)==false){
            alert("월을 다시 한번 확인하시고 입력해 주세요.");
          object.focus();
          return "";
        }
        if (num.length==6) {
         num = year+"/"+month;
        } else if (num.length==5) { 
         num = year+"/"+"0"+month;
        } 
    } else {
        num = "";
  window.alert("년월을 다시 한번 확인하시고 입력해 주세요.");
  object.focus();
        return "";
    } 
    return num;
}

/////////////////////////////////////////////////////
function isValidMonthYYYYMM(object, num) {
/////////////////////////////////////////////////////
//유효한(존재하는) 월(月)인지 체크 -- format_YYYYMM 에서만 사용
    if(num == "") return false;
 if(isNaN(num)) { 
  return false;
 }

 var m = parseInt(num,10);
 if(! (m >= 1 && m <= 12)){
  return false;
 } 
}

/////////////////////////////////////////////////////
function format_YYYYMMDD(object) {
/////////////////////////////////////////////////////
// 연월일(YYYYMMDD)의 유효성을 체크하고 표준 날짜 포맷 (YYYY/MM/DD) 으로 변환하여 리턴 (주의 : 이 함수의 파라미터는 객체임 (input object))

    var num, year, month, day;
    num=object.value;
    
    while (num.search("/") != -1){ 
      num = num.replace("/","");
 }
 
 if (isNaN(num)) {        
     window.alert("숫자로만 작성하셔야 합니다");
     object.focus();
     return "";
 }
    if( num != 0 && num.length == 8 ) {
        year = num.substring( 0, 4 );
        month = num.substring( 4, 6 );  
        day = num.substring(6);
        if(isValidDay(year,month,day)==false) {
         num = "";
         window.alert("유효하지 않는 일자입니다. 다시 한번 확인하시고 입력해 주세요.");
         object.focus();
         return "";
  }          
        num = year+"/"+month + "/" + day;
    } 
    else {
        num = "";
        window.alert("날짜 입력형식 오류입니다. 다시 한번 확인하시고 입력해 주세요.");
        object.focus();
        return "";
    } 
    return num;
}
/////////////////////////////////////////////////////
function format_YYYYMMDDHHMM(object) {
/////////////////////////////////////////////////////

    var num, year, month, day;
    num=object.value;
    
    while (num.search("/") != -1){ 
      num = num.replace("/","");
      num = num.replace(":","");
      num = num.replace(" ","");
 }
  
  if (isNaN(num)) {        
      window.alert("숫자로만 작성하셔야 합니다");
      object.focus();
      return "";
  }
   
    if( num != 0 && num.length == 12 ) {
        year = num.substring( 0, 4 );
        month = num.substring( 4, 6 );  
        day = num.substring(6,8);
  if(isValidDay(year,month,day)==false) {
         num = "";
         window.alert("유효하지 않는 일자입니다. 다시 한번 확인하시고 입력해 주세요.");
         object.focus();
         return "";
  }          
  hh = num.substring(8,10);
  if(isValidHour(hh)==false) {
         num = "";
         window.alert("유효하지 않는 시간입니다. 다시 한번 확인하시고 입력해 주세요.");
         object.focus();
         return "";
  }
  mm = num.substring(10,12);
  if(isValidMin(mm)==false) {
         num = "";
         window.alert("유효하지 않는 분입니다. 다시 한번 확인하시고 입력해 주세요.");
         object.focus();
         return "";
  }
  
        num = year+"/"+month + "/" + day+" "+hh+":"+mm;
    } 
    else {
        num = "";
        window.alert("날짜 입력형식 오류입니다. 다시 한번 확인하시고 입력해 주세요.");
        object.focus();
        return "";
    } 
    return num;
}


/////////////////////////////////////////////////////
function isDate(y,m,d)
/////////////////////////////////////////////////////
{
 var yy,mm,dd;

// if (!isNumber(y) || !isNumber(m) || !isNumber(d)) return false;
 yy = parseInt(y, 10);
 mm = parseInt(m, 10);
 dd = parseInt(d, 10);

 if (yy < 1900 || yy > 2200 ) return false;

 if (mm < 1 || mm > 12) return false;
 if (dd < 1) return false;
 if (mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm==10 || mm==12)
 {
  if (dd > 31) return false;
 }
 else if (mm==2)
 {
  if (isYunNyun(yy))
  {
   if (dd > 29) return false;
  }
  else {
   if (dd > 28) return false;
  }

 }
 else if (dd > 30) return false;
 return true;
}

/////////////////////////////////////////////////////
function isYM(y,m){
/////////////////////////////////////////////////////
// 날짜인지 체크 (년, 월)

 var yy,mm;
 if (!isNumber(y) || !isNumber(m)) return false;
 yy = parseInt(y, 10);
 mm = parseInt(m, 10);

 if (yy < 1900 ) return false;

 if (mm < 1 || mm > 12) return false;
 
 return true;
}

//=============================================================================
// Function  : setDateFormat(obj, index, obj2)
// Parameter : Obj     현재의 입력 객체      
//      index   객체의 인텍스 
//      obj2    타겟객체 
// Return    : NONE
// 기능      : 날짜format을 check  하고 두번째 객체의 값으로 할당한다.
//      obj[index]의 값을 yyyy/mm/dd 형식으로 변경하고 원래 입력값은 obj2[index]의 value로 할당한다.
//=============================================================================
function setDateFormat(obj, index, obj2) {
    val = delChar(obj.value, '/'); //comma filtering
    obj.value = val;
    
    a = isNumber(obj);
    var no = "";
    if (a == 1) {        
        if (obj2.length == "undefined" || obj2.length == null) {
            obj2.value = "";
        } else {
            obj2[index].value = "";
        }        
        return;
    }

    val = obj.value;
    len = val.length;
    
    if (len == 6) {
  no = format_YYYYMM(obj);  
 } else if (len == 8) {
  no = format_YYYYMMDD(obj);  
 }
        
 if (no == "") {
  obj.value = no;
 }
            
 if (obj2.length == "undefined" || obj2.length == null) {
  obj2.value = obj.value;
 } else {
  obj2[index].value = obj.value;
 }
 obj.value = no;
}


/////////////////////////////////////////////////////
function date_FormatYM(ym, formatmask){
/////////////////////////////////////////////////////
 // 날짜인지 체크 (년, 월)
 
  var fcount = formatmask.length;
  var len = trim(ym).length;
 var rv = "";
 ym = trim(ym);

 if (len == 6)
 {
  if (ym.substring(4, 5) == "/")
  {
   return  ym;
  }

  y = ym.substring(0, 4);
  m = ym.substring(4, 6);
 }
 else if (len == 7)
 {
  if (ym.substring(4, 5) != "/")
  {
   return  -1;
  }
  y = ym.substring(0, 4);
  m = ym.substring(5, 7);
 }
 else 
 {
  return ym; 
 }
 
 var ym_concat = y + m;
 var ret_ = -1;
 
 if((fcount == 7) && (formatmask == "????/??"))
 {
  if (isDateYM(ym_concat))
  {
   ret_ = y + "/" + m;
  }
  else
  {
   ret_ = -1;
  }
 }
 else
 {
  alert('Format["????/??"] 형식을 다시 한번 확인하시고 입력해 주세요.');
  ret_ = -1; 
 }
 
 return ret_;
}

/////////////////////////////////////////////////////
function isDateYM(ym){
/////////////////////////////////////////////////////
 var yy,mm;
 var y = "";
 var m = "";
 ym = trim(ym);
 y = ym.substring(0, 4);
 m = ym.substring(4, 6);

 if ( isYM(y, m) == true )
 {
  return true;
 }
 else
 {
  return false; 
 }
}

/////////////////////////////////////////////////////
function isYunNyun(y){
/////////////////////////////////////////////////////
// 운년인지 check.
 if ( (y % 4) == 0 )
 {
  if ((y % 100) != 0) return true;
  if ((y % 400) == 0) return true;
 }
 return false;
}

/////////////////////////////////////////////////////
function date_Format(ymd, formatmask){
/////////////////////////////////////////////////////
//  "20020204"의 날짜 문자열에 대한 formatting하기. 
  var fcount = formatmask.length;
  var len = trim(ymd).length;
 var rv = "";
 ymd = trim(ymd);

 if (len == 8)
 {
  if (ymd.substring(4, 5) == "/" )
  {
   return  ymd;
  }
  y = ymd.substring(0, 4);
  m = ymd.substring(4, 6);
  d = ymd.substring(6, 8);
 }
 else if (len == 9)
 {
  if (ymd.substring(4, 5) == "/")
  {
   if (ymd.substring(7, 8) == "/" )
   {
    return  ymd;
   }
   else  //yyyy/mmdd 형식
   {
    y = ymd.substring(0, 4);
    m = ymd.substring(5, 7);
    d = ymd.substring(7, 9);
   }
  }
  else
  {
   return  -1;
  }
 }
 else if (len == 10)
 {
  if (ymd.substring(4, 5) != "/" || ymd.substring(7, 8) != "/" )
  {
   return  -1;
  }
  y = ymd.substring(0, 4);
  m = ymd.substring(5, 7);
  d = ymd.substring(8, 10);
 }
 else 
 {
  return ymd; 
 }
 
 var ymd_concat = y + m + d;
 var ret_ = -1;
 
 if((fcount == 10) && (formatmask == "????/??/??"))
 {
  if (isDateYMD(ymd_concat))
  {
   ret_ = y + "/" + m + "/" + d;
  }
  else
  {
   ret_ = -1;
  }
 }
 else
 {
  alert('Format["????/??/??"] 형식을 다시 한번 확인하시고 입력해 주세요.');
  ret_ = -1; 
 }

 return ret_;
}

/////////////////////////////////////////////////////
function isDateYMD(ymd){
/////////////////////////////////////////////////////
// "20020204"의 날짜 문자열에 대한 formatting하기. 
 var yy,mm,dd;
 var y = "";
 var m = "";
 var d = "";

 y = ymd.substring(0, 4);
 m = ymd.substring(4, 6);
 d = ymd.substring(6, 8);

 if(isNaN(y) || isNaN(m) || isNaN(d)){
  return false; 
 }

 if ( isDate(y, m, d) == true )
 {
  return true;
 }
 else
 {
  return false; 
 }
}

/////////////////////////////////////////////////////
function isDateYYYY(yyyy){
/////////////////////////////////////////////////////
//년도 체크
 var yyyymmdd = yyyy + "0101";
 return isDateYMD(yyyymmdd);
}
/////////////////////////////////////////////////////
function isDateYYYYMM( yyyymm ){
/////////////////////////////////////////////////////
//년-월 체크

 var returnValue = false;
 var len = trim(yyyymm).length;
 yyyymm = trim(yyyymm);
 
 if( len == 7 )
 {
  if( yyyymm.substring(4, 5) == "/" )
  {
   returnValue = isYM( yyyymm.substring(0, 4), yyyymm.substring(5, 7) );
  }
 }
 else if( len == 6 )
 {
  returnValue = isYM( yyyymm.substring(0, 4), yyyymm.substring(4, 6) );
 }

 return returnValue;
}

/////////////////////////////////////////////////////
function isValidHour(hh) {
/////////////////////////////////////////////////////
// 유효한(존재하는) 시(時)인지 체크
    var h = parseInt(hh,10);
    return (h >= 1 && h <= 24);
}

/////////////////////////////////////////////////////
function isValidMin(mi) {
/////////////////////////////////////////////////////
// 유효한(존재하는) 분(分)인지 체크
    var m = parseInt(mi,10);
    return (m >= 1 && m <= 60);
}

/////////////////////////////////////////////////////
function isValidTimeFormat(time) {
/////////////////////////////////////////////////////
// Time 형식인지 체크(느슨한 체크)
    return (!isNaN(time) && time.length == 12);
}

/////////////////////////////////////////////////////
function isValidTime(time) {
/////////////////////////////////////////////////////
// 유효하는(존재하는) Time 인지 체크 년/월/일 만을(시간,분 제외) 검사. 
    var year  = time.substring(0,4);
    var month = time.substring(4,6);
    var day   = time.substring(6,8);
    //var hour  = time.substring(8,10);
    //var min   = time.substring(10,12);

    if (parseInt(year,10) >= 1900  && isValidMonth(month) &&isValidDay(year,month,day)){
     //&& isValidHour(hour)   && isValidMin(min)) {
        return true;
    }
    return false;
}

/////////////////////////////////////////////////////
function toTimeObject(time) { //parseTime(time)
/////////////////////////////////////////////////////
// Time 스트링을 자바스크립트 Date 객체로 변환  parameter time: Time 형식의 String
    var year  = time.substr(0,4);
    var month = time.substr(4,2) - 1; // 1월=0,12월=11
    var day   = time.substr(6,2);
    var hour  = time.substr(8,2);
    var min   = time.substr(10,2);

    return new Date(year,month,day,hour,min);
}

 

/////////////////////////////////////////////////////
function toTimeString(date) { //formatTime(date)
/////////////////////////////////////////////////////
// 자바스크립트 Date 객체를 Time 스트링으로 변환 
// parameter date: JavaScript Date Object
    var year  = date.getFullYear();
    var month = date.getMonth() + 1; // 1월=0,12월=11이므로 1 더함
    var day   = date.getDate();
    var hour  = date.getHours();
    var min   = date.getMinutes();

    if (("" + month).length == 1) { month = "0" + month; }
    if (("" + day).length   == 1) { day   = "0" + day;   }
    if (("" + hour).length  == 1) { hour  = "0" + hour;  }
    if (("" + min).length   == 1) { min   = "0" + min;   }

    return ("" + year + month + day + hour + min)
}

/////////////////////////////////////////////////////
function isFutureTime(time) {
/////////////////////////////////////////////////////
// Time이 현재시각 이후(미래)인지 체크
    return (toTimeObject(time) > new Date());
}

/////////////////////////////////////////////////////
function isPastTime(time) {
/////////////////////////////////////////////////////
// Time이 현재시각 이전(과거)인지 체크
    return (toTimeObject(time) < new Date());
}

/////////////////////////////////////////////////////
function shiftTime(time,y,m,d,h) { //moveTime(time,y,m,d,h)
/////////////////////////////////////////////////////
// 주어진 Time 과 y년 m월 d일 h시 차이나는 Time을 리턴
    var date = toTimeObject(time);
    date.setFullYear(date.getFullYear() + y); //y년을 더함
    date.setMonth(date.getMonth() + m);       //m월을 더함
    date.setDate(date.getDate() + d);         //d일을 더함
    date.setHours(date.getHours() + h);       //h시를 더함
    return toTimeString(date);
}

/////////////////////////////////////////////////////
function getMonthInterval(time1,time2) { //measureMonthInterval(time1,time2)
/////////////////////////////////////////////////////
// 두 Time이 몇 개월 차이나는지 구함
    var date1 = toTimeObject(time1);
    var date2 = toTimeObject(time2);

    var years  = date2.getFullYear() - date1.getFullYear();
    var months = date2.getMonth() - date1.getMonth();
    var days   = date2.getDate() - date1.getDate();

    return (years * 12 + months + (days >= 0 ? 0 : -1) );
}

/////////////////////////////////////////////////////
function getDayInterval(time1,time2) {
/////////////////////////////////////////////////////
// 두 Time이 며칠 차이나는지 구함
    var date1 = toTimeObject(time1);
    var date2 = toTimeObject(time2);
    var day   = 1000 * 3600 * 24; //24시간

    return parseInt((date2 - date1) / day, 10) + 1;
}

/////////////////////////////////////////////////////
function getHourInterval(time1,time2) {
/////////////////////////////////////////////////////
// 두 Time이 몇 시간 차이나는지 구함
    var date1 = toTimeObject(time1);
    var date2 = toTimeObject(time2);
    var hour  = 1000 * 3600; //1시간

    return parseInt((date2 - date1) / hour, 10);
}

/////////////////////////////////////////////////////
function getRelativeTime(y,m,d,h) {
/////////////////////////////////////////////////////
// 현재 시각과 y년 m월 d일 h시 차이나는 Time을 리턴
    return shiftTime(getCurrentTime(),y,m,d,h);
}

/////////////////////////////////////////////////////
function isFormatDate(ymd, formatmask){
/////////////////////////////////////////////////////
//9999/99/99 가 날짜인지
  var len_ymd = trim(ymd).length;
  var fcount = formatmask.length;

 if (len_ymd != 10)
 {
  return -1; 
 }
 
 if((fcount == 10) && (formatmask == "????/??/??"))
 {
  if (ymd.substring(4, 5) != "/" || ymd.substring(7, 8) != "/" )
  {
   return  -1;
  }
  y = ymd.substring(0, 4);
  m = ymd.substring(5, 7);
  d = ymd.substring(8, 10);

  var ymd_concat = y + m + d;
  var ret_value = -1;

  if (isDateYMD(ymd_concat))
  {
   ret_value = y + "/" + m + "/" + d;
  }
  else
  {
   ret_value = -1;
  }
 }
 else
 {
  alert('Format["????/??/??"] 형식을 다시 한번 확인하시고 입력해 주세요.');
  ret_value = -1; 
 }
 
 return ret_value;
}

/////////////////////////////////////////////////////
function isFormatDateYM(ym, formatmask) {
/////////////////////////////////////////////////////
//9999/99 가 날짜인지
  var len_ym = trim(ym).length;
  var fcount = formatmask.length;

 if (len_ym != 7)
 {
  return -1; 
 }
 
 if((fcount == 7) && (formatmask == "????/??"))
 {
  if (ym.substring(4, 5) != "/")
  {
   return  -1;
  }
  y = ym.substring(0, 4);
  m = ym.substring(5, 7);

  var ymd_concat = y + m + "01";
  var ret_value = -1;

  if (isDateYMD(ymd_concat))
  {
   ret_value = y + "/" + m;
  }
  else
  {
   ret_value = -1;
  }
 }
 else
 {
  alert('Format["????/??"] 형식을 다시 한번 확인하시고 입력해 주세요.');
  ret_value = -1; 
 }
 
 return ret_value;

}

 

/////////////////////////////////////////////////////
function DateCmp(date1, date2){
/////////////////////////////////////////////////////
//날자 크기 비교 입력형식 yyyy/mm/dd 또는 yyyymmdd
//ret = 0  if date1 == date2
//ret = 1  if date1 >  date2
//ret = -1 if date1 <  date2
 var s_date1 = date1 + ""; 
 var s_date2 = date2 + ""; 
 var ret = -2;
 
 if (s_date1 == s_date2)
 {
  ret = 0;
 }
 else if (s_date1 > s_date2)
 {
  ret = 1;
 }
 else if (s_date1 < s_date2)
 {
  ret = -1;
 }
 
 if (ret == -2)
 {
  alert("날자 비교가 잘못 되었습니다. 다시 한번 확인하시고 입력해 주세요.");
 }
 
 return ret;
}
// 해당 년월일의 요일 가져오기
function cala_day(year, month, day) {
 var nDayOfWeek = cala_weekday(month, day, year); 
 return day_display(nDayOfWeek)


// 해당 년월일에 따른 요일 계산하기
function cala_weekday( x_nMonth, x_nDay, x_nYear) {
  

        if(x_nMonth >= 3){         
                x_nMonth -= 2; 
        } 
        else { 
                x_nMonth += 10; 
        } 

        if( (x_nMonth == 11) || (x_nMonth == 12) ){ 
                x_nYear--; 
        } 

        var nCentNum = parseInt(x_nYear / 100); 
        var nDYearNum = x_nYear % 100; 

        var g = parseInt(2.6 * x_nMonth - .2); 

        g +=  parseInt(x_nDay + nDYearNum); 
        g += nDYearNum / 4;         
        g = parseInt(g); 
        g += parseInt(nCentNum / 4); 
        g -= parseInt(2 * nCentNum); 
        g %= 7; 
         
        if(x_nYear >= 1700 && x_nYear <= 1751) { 
                g -= 3; 
        } 
        else { 
   if(x_nYear <= 1699) { 
     g -= 4; 
   } 
        } 
         
        if(g < 0){ 
                g += 7; 
        } 
         
        return g; 


//요일 보여주기
function day_display(x_nDayOfWeek) { 

 if(x_nDayOfWeek == 0) return "일"; 
 if(x_nDayOfWeek == 1) return "월"; 
 if(x_nDayOfWeek == 2) return "화"; 
 if(x_nDayOfWeek == 3) return "수"; 
 if(x_nDayOfWeek == 4) return "목"; 
 if(x_nDayOfWeek == 5) return "금"; 
 if(x_nDayOfWeek == 6) return "토"; 




//년월일 포멧을 맞춰 준다.
//예 2000년 3월 2일 ====> 2000년 03월 02일
function convertDate(sfrYear, sfrMonth, sfrDay) {

 var sYear = sfrYear.value ;
 var sMonth = sfrMonth.value ;
 var sDay = sfrDay.value ;
 
 
 if ((sYear == null || sYear == "") && (sMonth == null || sMonth == "" )&& (sDay == null || sDay == "" ))
  return;


 if (isNaN(sYear))
  sYear = "";
 if (isNaN(sMonth))
  sMonth = "";
 if (isNaN(sDay))
  sDay = "";
 
 if (sYear == null || sYear == "" ) {
  sfrYear.value = "";
  return;
 }
 if (sMonth == null || sMonth == "" ) {
  sfrMonth.value = "";
  return;
 }
 if (sDay == null || sDay == "" ) {
  sfrDay.value = "";
  return;
 }
  

 var iYear=parseInt(sYear,10);
 var iMonth=parseInt(sMonth,10);
 var iDay=parseInt(sDay,10);

 if( iMonth<10 ) sMonth="0"+iMonth;
 else sMonth=""+iMonth;
 if( iDay<10)sDay="0"+iDay;
 else if( iDay<29)sDay=""+iDay;
 if(iYear<10 ){
  sYear="000"+iYear;
 } else if(iYear<100 ){
  sYear = "00"+iYear;
 } else if(iYear<1000 ){
  sYear = "0"+iYear;
 }else sYear = ""+iYear;
 
 sfrYear.value = sYear;
 sfrMonth.value = sMonth;
 sfrDay.value = sDay; 
}


//유효한 날짜 인지 체크 한다.
function checkDate(sfrYear, sfrMonth, sfrDay) {

 var sYear = sfrYear.value ;
 var sMonth = sfrMonth.value ;
 var sDay = sfrDay.value ;

 if (sYear == null || sYear == "" || sMonth == null || sMonth == "" || sDay == null || sDay == "" ){
  return "false";
 }

 var iYear=parseInt(sYear,10);
 var iMonth=parseInt(sMonth,10);
 var iDay=parseInt(sDay,10);

 if( iMonth<1 || iMonth>12 ){
   return "false";
 }
  
 if( iDay<1 || iDay > 31){
  return "false";
 }
 
 if( iMonth<10 ) sMonth="0"+iMonth;
 else sMonth=""+iMonth;
 if( iDay<10)sDay="0"+iDay;
 else if( iDay<29)sDay=""+iDay;
 else {
  if(iMonth==2){
   if  (( ( iYear%400 == 0 ) || ( ( iYear%100 != 0 ) && ( iYear%4 == 0 ) ) ) ) { if (iDay>29) { return "false";}}
   else if (iDay>28) return "false";
  }else if(iMonth==4 || iMonth==6 || iMonth==9 || iMonth==11){
   if(iDay>30 ) return "false";
  }else{
   if(iDay>31 ) return "false";
  }
 }
 if(iYear<10 ){
  sYear="000"+iYear;
 } else if(iYear<100 ){
  sYear = "00"+iYear;
 } else if(iYear<1000 ){
  sYear = "0"+iYear;
 }else sYear = ""+iYear;
 sfrYear.value = sYear;
 sfrMonth.value = sMonth;
 sfrDay.value = sDay;
 return "true";
  
}


// 쓰여진 공백을 제거하고, 생년월일의 입력이 올바른지 체크
// (2004.07.13 for KNTO by 고상원)
// 매개변수 : year,month,date (form의 input type=text 객체)
//
// 입력이 틀린부분이 있으면
// 1. 메시지를 출력하고
// 2. 해당부분에 focus()를 호출하고
// 3. false를 return한다.
// 입력이 모두 맞으면 true를 리턴한다.
// (자릿수가 1자리인 월,일에는 앞에 0을 붙인다.)
function isValidBirthdateInput(year, month, date) {

 // 공백제거
 year.value = year.value.replace(/ /gi,"");
 month.value = month.value.replace(/ /gi,"");
 date.value = date.value.replace(/ /gi,"");

 // 년
 if (year.value.length != 4 || isNaN(year.value)) {
  alert("해당 년을 다시 한번 확인하시고 입력해 주세요.");
  year.focus();
  return false;
 }

 // 월
 if (!isValidMonthCheck(month.value)) {
  alert("해당 월을 다시 한번 확인하시고 입력해 주세요.");
  month.focus();
  return false;
 }
 else if (month.value.length == 1)
  month.value = "0" + month.value;

 // 일
 if (!isValidDay(year.value, month.value, date.value)) {
  alert("해당 날짜를 다시 한번 확인하시고 입력해 주세요.");
  date.focus();
  return false;
 }
 else if (date.value.length == 1)
  date.value = "0" + date.value;

 return true;
}

// 선택한 포맷으로 날짜형식을 정한다.
function make_date_format(strDate, strformat){

 if(strDate != null) {
  if ( strDate.length == 8) {
   str = strDate.substring(0,4) + strformat + strDate.substring(4,6) + strformat + strDate.substring(6,8); //날짜
  }
 }

 return str ;
}

Posted by useways
,

두 날짜사이의 지난 시간을 계산합니다.

 

일,시간,분,초

 

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

  var strFromDate = "201012011500"; //시작시간
  var strToDate   = "201012021501"; //종료시간
  
  var fromDate = new Date(strFromDate.substring(0,4),
        strFromDate.substring(4,6)-1,
        strFromDate.substring(6,8),
        strFromDate.substring(8,10),
        strFromDate.substring(10,12)
       );
       
  var toDate = new Date(strToDate.substring(0,4),
        strToDate.substring(4,6)-1,
        strToDate.substring(6,8),
        strToDate.substring(8,10),
        strToDate.substring(10,12)
       );
    
  daysAfter = (toDate.getTime() - fromDate.getTime()) / (1000*60*60*24);
  hourAfter = (toDate.getTime() - fromDate.getTime()) / (1000*60*60);
  minAfter = (toDate.getTime() - fromDate.getTime()) / (1000*60);
  secAfter = (toDate.getTime() - fromDate.getTime()) / (1000);
  
  daysAfter = Math.round(daysAfter);
  hourAfter = Math.round(hourAfter);
  minAfter = Math.round(minAfter);
  secAfter = Math.round(secAfter);
  
  document.write(daysAfter + "일 지났습니다."); // 지난 날짜 출력
  document.write("<br>" + hourAfter + "시간 지났습니다."); // 지난 시간 출력
  document.write("<br>" + minAfter + "분 지났습니다."); // 지난 분 출력
  document.write("<br>" + secAfter + "초 지났습니다."); // 지난 초 출력

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

[출처] [DATE] 날짜간 지난 시간 계산 자바스크립트|작성자 싸커마

'12 Javascript > 30 각종 함수' 카테고리의 다른 글

30 replace 문제점  (0) 2021.07.16
31 날자관련 각종 utils  (0) 2021.07.16
31 날자관련 날자계산  (0) 2021.07.16
인코더(Encoder), Eval함수 ,숫자변환함수  (0) 2021.07.15
31 날자관련 var d = new Date();  (0) 2018.07.18
Posted by useways
,

오늘 날짜를 기준으로 1주일,2주일,1개월이전날짜를 찍는걸로 만들었지만 버튼에 함수로 전달하는 파라메터를 조절하면 얼마든지 임의로 변경할 수 있겠습니다..^^

<html>
<head>
<title> 날짜 </title>
<script language="javascript">
<!--
function time(){
 var now = new Date;
 document.all.oo.innerText = "오늘은 " + now.getYear() + "년 " + (now.getMonth()+1) + "월 " + now.getDate() + "일 " + now.getHours() + "시 " + now.getMinutes() + "분 " + now.getSeconds() + "초 입니다.";

setTimeout("time()", 1000);

}

 

function setDay(t){// 일차를 파라메터로 받는다
 var now = new Date;
 var today = now.getYear() + "/" + (now.getMonth()+1) + "/" + now.getDate();//현재날짜
 document.date.date2.value = today; 
 document.date.date1.value = getThatday(today,t); //현재날짜와 일차를 파라미터로 보내서 결과리턴한다.
}

function getThatday(today,t){ //날짜, 일차를 파라메터로 받는다.
 var pdate=new Array(); 
 var pday=today.split("/"); //날짜를 구분자로 나누어 배열로 변환한다.
 var ptoday=new Date(pday[0],pday[1]-1,pday[2]); //데이트객체 생성한다.
 var ptimestamp=ptoday.valueOf()+1000*60*60*24*t; //t일후의 타임스탬프를 얻는다. 음수라면 이전날짜를 얻는다.
 var thatday=new Date(ptimestamp); //t일후의 날짜객체 생성한다.
 
 pdate[pdate.length]=thatday.getYear(); //년
 pdate[pdate.length]=thatday.getMonth()+1; //월
 pdate[pdate.length]=thatday.getDate(); //일
 return pdate.join("/"); //배열을 / 구분자로 합쳐 스트링으로 변환후 반환
}

 

//-->
</script>
</head>

<body onload="time()" >
<span id=oo></span>

<FORM METHOD=POST name="date" ACTION="">
 <INPUT TYPE="button" onclick="setDay(-7)" value="1주일">
 <INPUT TYPE="button" onclick="setDay(-14)" value="2주일">
 <INPUT TYPE="button" onclick="setDay(-30)" value="1개월">
 <br>
 <INPUT TYPE="text" NAME="date1">~<INPUT TYPE="text" NAME="date2">

</FORM>
</body>
</html>

 

출처 : 

https://blog.naver.com/PostView.nhn?isHttpsRedirect=true&blogId=basketyj&logNo=30129949743 

http://kimjongyeol.tistory.com/54

 

Posted by useways
,

 

===> 조건이 숫자일때 여러조건 같이 하는법
/* 기본의 case 구문*/

var data = 0;
switch (data)
{
case 5:
  document.write("<b>데이터는 5 입니다. </b>");
  break;
case 6:
  document.write("<b>데이터는 6 입니다. </b>");
  break;
case 0,1,2,3,4 :
  document.write("<b>데이터는 0~ 4 입니다. </b>");
  break;
default:
  document.write("<b>없는 데이터 입니다  </b>");
}


===> 조건이 문자일때 여러조건 같이 하는법

//weblogic 일때 jstl에서 xml 데이터 불러올때 있는 공백때문에 저장할때 미리 공백제거하는 부분
function form_trim(form9) {
//function SetValues(form9 , c) { 
    //alert("dddddddd"+form9.elements[1].name);
    //form9.elements[6].value = this.docXML.getElementsByTagName("rec_aftn1").item(0).firstChild.nodeValue;
    //form9.elements[7].value = this.docXML.getElementsByTagName("rec_aftn2").item(0).firstChild.nodeValue;
     len = form9.elements.length;
     //alert(len); 
    for (i = 0; i < len; i++) {
        //alert("ddddd"+form9.elements[i].type);
        switch (form9.elements[i].type) {
            case "radio":
            case "checkbox": 
                //alert(form9.elements[i].name);
                //if (this.docXML.getElementsByTagName(form9.elements[i].name).item(0).firstChild.nodeValue == "true") {
                // form.elements[i].checked == true 
                //} 
                break; 
            case "text" :
            case "select-one" :
            case "hidden" :
            case "textarea" :    
                //alert("ddddd"+form9.elements[i].name);  
                //alert("dddddddd"+form9.elements[i].name+"["+this.docXML.getElementsByTagName("fp_priority").item(0).firstChild.nodeValue+"]");
                //form9.elements[i].value = this.docXML.getElementsByTagName(form9.elements[i].name).item(0).firstChild.nodeValue;
                //var val10 =  c.find(form9.elements[i].name).text() ; 
             //val10 = val10.replace(/\n/g,"\r");
             form9.elements[i].value = trim_both_side(form9.elements[i].value);
                //form9.elements[i].value = val10;
                break;
        } 
    }  
  
  
}//end function. 

 

 

 

 

 


=====참고: http://dongsilove.tistory.com/99 

<script type="text/javascript">

// 숫자형으로 조건 지정
var i = 365;

switch (i) {
  case 66    : document.write('66 이라는 정수입니다.<br />');
               break;
  case 365   : document.write('365 라는 정수입니다.<br />');
               break;

case 1000  : document.write('1000 이라는 정수입니다.<br />');

               break;
default    : document.write('해당 숫자가 없습니다.<br />');
               break;
}
// 출력 결과: 365 라는 정수입니다.


// 문자형으로 조건 지정
var c = 'A';

switch (c) {
  case 'A'  : document.write('A 라는 문자입니다.<br />'); break;
  case '똠' : document.write('똠 이라는 문자입니다.<br />'); break;


// 문자형으로 조건 지정
var c = 'A';

switch (c) {
  case 'A'  : document.write('A 라는 문자입니다.<br />'); break;
  case '똠' : document.write('똠 이라는 문자입니다.<br />'); break;
  case '7'  : document.write('7 이라는 문자입니다.<br />'); break;
  default   : document.write('해당되는 문자가 없습니다.<br />'); break;
}
// 출력 결과: 'A' 라는 문자입니다.


// 문자열로 조건 지정
var camera = 'Nikon D40X';

switch (camera) {
  case 'Nikon D40'  : document.write('50만원대입니다.<br />'); break;
  case 'Nikon D40X' : document.write('80만원대의 디카입니다.<br />'); break;
  case 'Canon PowerShot' : document.write('40만원대의 컴팩트 카메라입니다.<br />'); break;
  default   : document.write('해당되는 카메라가 없습니다.<br />'); break;
}
// 출력 결과: 80만원대의 디카입니다.

</script>



'12 Javascript > 10 기초부분' 카테고리의 다른 글

00 자바스크립트란?  (0) 2021.07.29
---20 객체와 배열이란?  (0) 2021.07.29
10 Function(함수)  (0) 2021.07.15
10 제어문(if 문 , for 문)  (0) 2021.07.15
10 변수의 선언  (0) 2021.07.15
Posted by useways
,

객체를 선언한후 변수를 추가할수 있다. 변수뿐아니라 함수또한 가능함

Delete를 사용하여 삭제도 가능하다 .

 

<script type="text/javascript">

    var student = {};

    //변수 추가

    student.name='CNJ';

    student.major='Computer science';

    student.grade='A';

    

    //메서드 추가

    student.toString = function(){

        var output ='';

        for(var key in this){

            if(key!='toString'){

                output+=key+' : '+this[key]+'\n';

            }

        }

        return output;

    };

    console.log(student.toString());

    

    //변수삭제

    delete(student.grade);

    console.log(student.toString());

    

    </script>

 

 

 

 

 

student배열을 선언한후,

push를 이용하여 객체를 하나씩 넣어준다.

객체안에 메소드를 추가하여 사용한다.

 

    <script type="text/javascript">

    

    var student= [];

    student.push({이름: '윤일성',국어:97,수학 :55,영어:30});

    student.push({이름: '조남재',국어:100,수학 :98,영어:99});

    student.push({이름: '이재백',국어:33,수학 :44,영어:55});

    student.push({이름: '김성준',국어:57,수학 :75,영어:70});

    

    for(var i in student){

        student[i].getSum=function(){

            return this.국어+this.수학+this.영어;

        }

        

        student[i].getAverage= function(){

            return this.getSum()/4;

        }

    }

    var output ='이름 \t 총점\t평균\n';

    for(var i in student){

        with(student[i])

            output+=이름+' \t'+getSum()+' \t'+getAverage()+'\n';

    }

    console.log(output);

    </script>

 

 

 

 

생성자

 

<script type="text/javascript">

    function Student(name,korean,math,english){

        this.name=name;

        this.korean=korean;

        this.math=math;

        this.english = english;

        

        this.getSum= function() {

            return this.korean+this.math+this.english;

        }

        this.getAVG= function() {

            return this.getSum()/3;

        }

        this.toString= function() {

            return this.name+'\t'+this.getSum()+'\t'+this.getAVG();

        }

    }

    

    var student=[];

    student.push(new Student('kim',94,65,84));

    student.push(new Student('park',78,84,76));

    student.push(new Student('sung',92,43,93));

    

    var output='이름\t총점\t평균\n';

    for(var i in student){

        output+=student[i].toString()+'\n';

    }

    console.log(output);

</script>

 

출처

https://blog.naver.com/PostView.naver?blogId=skawo32167&logNo=220453504108&parentCategoryNo=&categoryNo=50&viewDate=&isShowPopularPosts=false&from=postList

Posted by useways
,

요약

 var product ={

        name : '조남재',

        type : '타입은 객체',

        eat : function(food){

                alert(this.name+ '이가'+ food+ '을먹는다.');

            }

}

    console.log(typeof(product));  //object 찍힘

    console.log(product['name']); 

    console.log(product.type);

    product.eat('고기');

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

객체 생성 및 접근

<script type="text/javascript">

// 객체 생성

    var product ={

        name : '조남재',

        type : '타입은 객체',

        component:'나는야조남재',

        made : '코리아',

}

    console.log(typeof(product));

    

    console.log(product['name']);

    console.log(product['type']);

    

    console.log(product.component);

    console.log(product.made);

 

 

</script>

 

 

객체내에 함수도 넣을수 있다.

객체내의 함수를 메소드라한다.

 

    var person ={

            name: '조남재',

            eat : function(food){

                alert(this.name+ '이가'+ food+ '을먹는다.');

            }

    };

    

    person.eat('고기');

 

 

for문으로 객체정보 사용하기.

<script type="text/javascript">

    var product = {

        name: 'Microsoft Visual Studio 2012',

        price: '15,000,000',

        language: '한국어',

        supportOS: 'window 32/64',

        subscription :true

    };

    

    var output='';

    for(var key in product){

        output +=key + " : " + product[key]+'\n';

    }

    alert(output);

    

</script>

 

 

 

객체 in 변수

 

 

<script type="text/javascript">

    var output ='';

    var student={

            name:'남재',

            math:100, english: 90,science: 85, history: 80

    };

    //잇는거

    output+= '"name" in student:'+('name' in student)+'\n';

    //없는거

    output+= '"gender" in student:'+('gender' in student)+'\n';

    

    alert(output);

 

</script>

 

In 을 사용하여 객체내에 변수가 있는지 없는지 확인할수있음.

 

With

With를 사용하여 객체내 속성, 변수를 간편하게 사용가능

단 없는 것을 사용하면 error (in 같이 검출기능은 X)

 

<script type="text/javascript">

    var output ='';

    var student={

            name:'남재',

            math:100, english: 90,science: 85, history: 80

    };

    

    with(student){

        output+='name : ' + name+'\n';

        output+='math : ' + math+'\n';

        output+='english : ' + english+'\n';

        output+='science : ' + science+'\n';

        output+='history : ' + history+'\n';

        output+='total : ' + (math+english+science+history)+'\n';

    }

    alert(output);

</script>

에러가나기 때문에 abc를 지우고 다시 실행!

 

 

출처

https://blog.naver.com/PostView.naver?blogId=skawo32167&logNo=220453503896&parentCategoryNo=&categoryNo=50&viewDate=&isShowPopularPosts=false&from=postList

 

Posted by useways
,

인코더와 디코더

 

script type="text/javascript">

var URI='http:\\hanb.co.kr?test=한글입니다.';

var output='';

output+= 'escape()\n';

output+=escape(URI)+'\n\n';

 

output+= 'escape()URi\n';

output+=encodeURI(URI)+'\n\n';

 

output+= 'escape()URIComponent()\n';

output+=encodeURIComponent(URI)+'\n\n';

 

alert(output);

console.log(output);

</script>

 

 

 

Eval 코드 실행함수

문자열이나 코드스트링을 실행문으로 바꿔주는함수

문자열을 실행시킨다. '1+1' 이나

var number=10;

alert(number);

 실행시킨다.

 

<script type="text/javascript">

 

console.log('1+1');

 

//문자열 => 표현식

console.log(eval('1+1'));

 

 

// 실행코드로 바꿔줌

var willEval ='';

willEval += 'var number=10;';

willEval+= 'alert(number);';

eval(willEval);

 

</script>

 

 

 

 

숫자변환함수

 

<script type="text/javascript">

 

var won = '1000';

var dollar ='1.5$';

alert(Number(won)+' : '+Number(dollar));

</script>

<script type="text/javascript">

 

var won = '1000';

var dollar ='1.5$';

alert(parseInt(won)+' : '+parseInt(dollar));

alert(parseFloat(won)+' : '+parseFloat(dollar));

</script>

 

숫자로 변환할수있는것만 바꿔준다.

그러나 parse도 여러 개 이상현상이 있으니 확인하고 바꿔서 사용해야한다.

 

출처

https://blog.naver.com/PostView.naver?blogId=skawo32167&logNo=220452876237&parentCategoryNo=&categoryNo=50&viewDate=&isShowPopularPosts=false&from=postList

Posted by useways
,

재사용성을위해 function 함수사용

 

<script type="text/javascript">

function func1(){

    console.log('func1() 호출')

}

//

    func1();

    func1();

</script>

 

 

매개변수를이용한 함수 (Function)

 

function func2(data1, data2){

    console.log('func2(1)'+data1);

    console.log('func2(2)'+data2);

}

//

 

    func2(1,2);

 

 

Return 값, 매개변수값 잇는 함수(function)

 

function func3(data1, data2){

    var sum=data1+data2;

    return sum;

}

var sum=func3(10,20);

    console.log("결과 : "+ sum)

 

또다른 선언방식(익명함수)

  • 익명함수는 선언적 함수보다 늦게 생성됨
  • (같은이름으로 선언했을시 익명함수가 남아있음.)
  • 왜냐하면 선어적함수는 코드가 실행되기전 한번선언이되고 시작됨.

//함수들 변수와 동일하게 취급

    var func1 = function(){

        console.log('func1() 호출');

    };

func1();

    console.log(typeof(func1));

    

    var func2= func1;

    func2()

    

 

가변인자 function 함수

    function sumAll(){

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

            console.log(arguments[i]);

        }

    }

    sumAll(1);

    sumAll(1,2);

 

 

 

리턴값이 Function(함수)인 Function(함수)

 

function returnFunction(){

    return function(){

        console.log('Hello Function ..!');

    }

}

returnFunction()();

 

 

 

 

 

내장함수

 

타이머

setTimeout(function,시간 밀리세턴); - 일정시간후 함수 한번 실행

setinterval(함수, 시간) 일정시간마다 함수실행

clearTimeout(id) – 일정시간후 함수를 한번 실핸하는 것을 중지

clearintervla(id) – 일정시간마다 함수를 반복하는 것을 중단합니다.

 

 

<script type="text/javascript">

 

var intervalID = setInterval(function(){

    console.log('<p>'+new Date()+'</p>');

},1000);

</script>

 

 

출처

https://blog.naver.com/PostView.naver?blogId=skawo32167&logNo=220452876212&parentCategoryNo=&categoryNo=50&viewDate=&isShowPopularPosts=false&from=postList

'12 Javascript > 10 기초부분' 카테고리의 다른 글

---20 객체와 배열이란?  (0) 2021.07.29
11 switch case문  (1) 2021.07.16
10 제어문(if 문 , for 문)  (0) 2021.07.15
10 변수의 선언  (0) 2021.07.15
10 출력문(document.write // Console.log //alert)  (0) 2021.07.15
Posted by useways
,

if문은 자바의 문법과 동일하다.

 

 

<script type="text/javascript">

var hakjum=prompt("학점을 입력하세요", 75);

if(hakjum>80){

    alert(hakjum+"점은 A입니다.")

}else if(hakjum>70){

    alert(hakjum+"점은 B입니다.")

}else if(hakjum>60){

    alert(hakjum+"점은 C입니다.")

}else{

    alert(hakjum+"점은 D입니다.")

}

</script>

 

 

for문돌려서 구구만 table 생성하기

<script type="text/javascript">

    var start=1;

    var end=9;

    document.write("<table border solid 1px>");

    document.write("<tr><td> </td>");

    for(var i=1;i<10;i++){

        document.write("<td>X"+i+"</td>");

    }

    document.write("</tr>");

    for(var i=start; i<=end;i++){

        document.write("<tr>");

        document.write("<td>"+i+"</td>");

        for(var j=1;j<10;j++ ){

            var result=i*j;

            document.write("<td>"+i+"x"+j+"="+result+"</td>");

        }

        document.write("</tr>");

    }

    document.write("</table>");

</script>

 

출처

https://blog.naver.com/PostView.naver?blogId=skawo32167&logNo=220452876160&parentCategoryNo=&categoryNo=50&viewDate=&isShowPopularPosts=false&from=postList

'12 Javascript > 10 기초부분' 카테고리의 다른 글

11 switch case문  (1) 2021.07.16
10 Function(함수)  (0) 2021.07.15
10 변수의 선언  (0) 2021.07.15
10 출력문(document.write // Console.log //alert)  (0) 2021.07.15
10 Java Script 개요와 개발환경설정  (0) 2021.07.15
Posted by useways
,

변수의 선언

var를 이용해 선언한다

데이터형은 선언하지않아도 자동적으로 입력이된다.

데이터형 가변형인자이다 .

<script type="text/javascript">

    var radius=10;

    var pi= 3.14159265;

    alert(2*pi*radius);

</script>

 

변수의 데이터형 확인

typeof

 

<script type="text/javascript">

    console.log(typeof('String'));

    console.log(typeof(273));

    console.log(typeof(true));

    console.log(typeof(function(){}));

    console.log(typeof({}));

 

    var test

    console.log(typeof(test))

    

</script>

 

증감 연산자

<script type="text/javascript">

    var list='';

    list+='<ul>';

    list+='    <li>hello</li>';

    list+=' <li>java script....</li>';

    list+='</ul>';

    

    document.write(list);

 

변수의 재선언

javascript엔 변수의 재선언이 가능함..

그러므로 변수명을 잘 선언하도록해야함

 

<script type="text/javascript">

    var favoriteFood="김치찌게";

    var favoriteFood="딸기";

    var favoriteFood="사과";

    

    //출력합니다

    alert(favoriteFood);

</script>

 

 

 

변수를 var선언하지 않고도 선언되는경우도 있다 .

    alert(typeof(variable));

    variable="ss"

    alert(variable);

보통이라면 variable이 선언이 되지않아서 , 오류가 떠야하지만

java script에서는 변수가 선언이되어 실행이된다.

 

 

=== 3번은 자료형과 내용이 같은것

!== 자료형과 내용이 다른것

 

<script type="text/javascript">

console.log(''===false);

console.log(''===0);

console.log(0===false);

console.log('273'===273);

 

</script>

 

 

출처

https://blog.naver.com/PostView.naver?blogId=skawo32167&logNo=220452876137&parentCategoryNo=&categoryNo=50&viewDate=&isShowPopularPosts=false&from=postList

'12 Javascript > 10 기초부분' 카테고리의 다른 글

11 switch case문  (1) 2021.07.16
10 Function(함수)  (0) 2021.07.15
10 제어문(if 문 , for 문)  (0) 2021.07.15
10 출력문(document.write // Console.log //alert)  (0) 2021.07.15
10 Java Script 개요와 개발환경설정  (0) 2021.07.15
Posted by useways
,

출력문1

<script type="text/javascript">

    document.write("Hello javascript<br>");

    /*

        html 생성, 띄어쓰기 <br> 써야함.

        

        DOM(Document Object Model) - Tree =>DOM Tree

        

        브라우저 html 문서을 읽으면 메모리에 DOM Tree 생성

        자바스크립트 메모리 안에 Dom Tree 수정

        

        확인방법

        DOM 탐색기 (자바스크립트 -> html코드로 바꿈 (소스보기엔 바뀐코드가 나옴.))

        

    */

    document.write("<b>Hello javascript</b>");

</script>

HtmL문서의 출력문으로 결과가난다 .

 

 

 

 

 

또다른 출력문2.(개발자 출력문)

 

<script type="text/javascript">

    console.log("Hello javascript");

</script>

홈페이지가 아닌 F12 콘솔창에서 볼수있으며

중간중간의 정보를 확인하기위해 사용한다.

 

 

출력3 (에러출력)

<script type="text/javascript">

    alert("Hello");

</script>

 

출처

https://blog.naver.com/PostView.naver?blogId=skawo32167&logNo=220452876061&parentCategoryNo=&categoryNo=50&viewDate=&isShowPopularPosts=false&from=postList

'12 Javascript > 10 기초부분' 카테고리의 다른 글

11 switch case문  (1) 2021.07.16
10 Function(함수)  (0) 2021.07.15
10 제어문(if 문 , for 문)  (0) 2021.07.15
10 변수의 선언  (0) 2021.07.15
10 Java Script 개요와 개발환경설정  (0) 2021.07.15
Posted by useways
,

요약

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

html5 + css3 + javascript

 

1. 브라우저 웹사이트(웹페이지)

    =>chrome Web Store

    =>브라우저 인스톨할 수 있는 프로그램(app store)

    =>chrome OS ( web OS)

    =>Ms Store

2. 안드로이드 / 아이폰용 프로그램

    직접설치(하이브리드앱) / 브라우저(모바일웹)

=>

3. wearable 기기

    => Smart Tv

 

java Script 에는 여러종류가 있엇고

모두의 문제는 해석기의 속도였는데

google에서 v8 engine으로 새로운 해석기를 만듬

 

v8 engine

    브라우저 밖

        1.액션 스크립트

        2.Unity 스크립트

        3.node.js

 

Script 언어 -소스 = 실행파일

compile 언어 -> 소스 -> 실행파일 -> 실행

 

* 그러므로 Script는 소스코딩이 중요하다

소스 코딩

    메모장 / 에디트 플러스

    IDE(통합개발환경) - eclipse(이클립스)

            -> apatana ( java스크립스 전용 이클립스 ) but 너무느려서 안쓰임

            -> webstorm --> www.jetbrains.com

            -> visual studio

 

 

이클립스

help -> eclipse Market

 

jsdt 검색

설치후

 

dynamic web project 생성

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<script type="text/javascript">

    alert("Hello");

</script>

 

</body>

</html>

 

java Script를 사용하는 두번째방법

new- other java script sorce를 만든후

js언어를 사용해준다.

<script type="text/javascript" src="js01.js">

</script>

사용한다 .결과는같고

 

오류 검출은 f12를 누르고 새로고침으로 찾아낼수있다.

js는 오류가나도 실행되는경우가 대부분이라 오류를 찾기 위해 f12관리자 모드를이용해 확인해봐야한다.

 

 

출처

https://blog.naver.com/PostView.naver?blogId=skawo32167&logNo=220452876014&categoryNo=50&parentCategoryNo=0&viewDate=¤tPage=9&postListTopCurrentPage=1&from=postList&userTopListOpen=true&userTopListCount=5&userTopListManageOpen=false&userTopListCurrentPage=9 

'12 Javascript > 10 기초부분' 카테고리의 다른 글

11 switch case문  (1) 2021.07.16
10 Function(함수)  (0) 2021.07.15
10 제어문(if 문 , for 문)  (0) 2021.07.15
10 변수의 선언  (0) 2021.07.15
10 출력문(document.write // Console.log //alert)  (0) 2021.07.15
Posted by useways
,

요약

var arr1=[73,32,103,42,4];
var arr2=new Array(273,32,103,42,4);

arr1.push(2);

//앞쪽부터검색 없으면 -1리턴
var output1 = array.indexOf(4);

//출력
    array.forEach(function(element,index,arr){
        console.log(index+"/"+element);
    });

    for(var i in array){
        console.log(array[i]);
    }

 

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

출처

https://blog.naver.com/PostList.naver?blogId=skawo32167&skinType=&skinId=&from=menu&userSelectMenu=true

<script type="text/javascript">

    var arr1=[73,32,103,42,4];

    var arr2=new Array(273,32,103,42,4);

    

    console.log(arr1[0]);

    console.log(arr2[0]);

    console.log(arr1.length);

    console.log(arr2.length);

    

    var arr=[0,1];

    arr.push(2);

    arr.push(3);

    arr.push(4);

    

    alert(arr);

      

    

</script>

 

 

 

 

 

 

배열에 검색기능을 사용할수있다.

 

<script type="text/javascript">

var array=[1,2,3,4,5,5,4,3,2,1];

//앞쪽부터검색 없으면 -1리턴

var output1 = array.indexOf(4);

var output2 = array.indexOf(8);

//뒤쪽부터 검새 없으면 -1리턴

var output3 = array.lastIndexOf(4);

var output4 = array.lastIndexOf(8);

 

var output ="";

output+=output1+" : "+output2+"\n";

output+=output3+" : "+output4;

console.log(output);

</script>

 

 

배열의 또다른 기능

<script type="text/javascript">

 

var array=["","","",""];

 

    array.forEach(function(element,index,arr){

        console.log(index+"/"+element);

    });

 

</script>

 

 

향상된 for문 배열

 

<script type="text/javascript">

var array=['포도','딸기','바나나','참외'];

 

for(var i in array){

    console.log(array[i]);

}

</script>

 

Posted by useways
,

var d = new Date(0;

var yyyymmdd = d.getFullYear() + (d.getMonth()+1).setDigit(2) +d.getDate().setDigit(2);

var hhmmss = d.getHours().setDigit(2) + d.getMinutes().setDigit(2) + d.getMilliseconds();



참고 사이트:

http://blog.naver.com/PostView.nhn?blogId=zeze3731&logNo=221313992348



Posted by useways
,

1. substring : 어디서부터 어디까지 잘라내겠다

(java의 substring과 같다)

2. substr : 어디서부터 몇번째까지 잘라내겠다

 


예제) "abcdefg" 라는 문자열이 있으면

substring(2, 4) 를 하면 "cd"의 결과가 나오고

substr(2, 4) 를 하면 "cdef"가 나온다.

 


substring의 뜻은 인덱스 2번째 문자에서 인덱스 4번째 문자까지를 가져오겠다는 뜻.

substr의 뜻은 인덱스 2번째 문자에서부터 뒤로 4개를 가져오겠다.

 

뒤에서 부터 4자리 가져오기

var _str = 'kimsungho';

var str = _str.substr(_str.length - 4, 4);

 

출처 http://useways.tistory.com/entry/

Posted by useways
,

페이지 로딩시 시작할 스크립트 선언에 대해 <body onload="">의 onload를 많이 사용해 보았을 것입니다.

<body onload="fillGridOnEvent();" bgcolor="#EDEDED">


그리고 모든 페이지에서 공통으로 들어갈 스크립트는 페이지 마다 작성을 하지 않고, js 파일을 만들어 연결을 하여 사용을 할 것입니다.

여기서 그럼 모든 페이지에서 load시 공통으로 실행될 스크립트는 어떻게 작업을 할까요??
window.onload를 사용 하면 됩니다.

window.onload = function(){ 시작시 실행될 내용 }이런식으로 말이죠.

그런데 문제는 window.onload와 <body onload="">는 동시에 사용을 할 수 없습니다.
<body onload="">가 실행이 되면 window.onload는 실행이 되지 않는 문제가 있습니다.

그래서 이를 해결하고자 할때 사용하는 것이 window::onload()입니다.

function window::onload(){ 시작시 실행될 내용 }
이렇게 사용을 하면 됩니다.

실행 순서는 <body onload="">가 먼저 실행되고, 이어서 window::onload()가 실행됩니다.

 

[simon]

방법 1.

function window::onload(){
 alert(opener.document.title);
 if(opener.document.title ="상세화면"){
  self.ifrMain.location = "airport_recsnowtam_into.jsp";
 }else{
  self.ifrMain.location = "airport_recsnowtam_into.jsp"; 
 }
}

방법 2.

window.onload = function cnj_alrtBox(){
 alert(opener.document.title);

 if(opener.document.title ="상세화면"){
  self.ifrMain.location = "airport_recsnowtam_into.jsp";
 }else{
  self.ifrMain.location = "airport_recsnowtam_into.jsp"; 
 }
}

방법 3.  이방법은 ifrMain 찾을수 없다고 하면서 에러난다.

window.onload=cnj_alrtBox();

function cnj_alrtBox(){
 alert(opener.document.title);

 if(opener.document.title ="상세화면"){
  self.ifrMain.location = "airport_recsnowtam_into.jsp";
 }else{
  self.ifrMain.location = "airport_recsnowtam_into.jsp"; 
 }
}

Posted by useways
,

출처: http://coding-start.tistory.com/35


JavaScript 타이머 함수

자바스크립트에서 타이머함수란 전역객체인 window 객체 안에 있는 함수들입니다. 그렇다면 타이머 함수가 할수 있는 일은 무엇이 있을까요?

 

1. 특정시간마다 특정 함수를 계속 호출해서 실행 시킬 수 있다. => setInterval(function, duration)

참고 http://gemuse.tistory.com/28

예제 :         window.setInterval( function(){
                                             scope.setColhead();
                                          },1000);

2. 특정시간 이후에 딱 한번만 특정함수를 호출해 실행시킨다. => setTimeOut(function, duration)

예제 : setTimeout(function(){self.doSearch();},300);

참고 http://travelfacebook.tistory.com/2260

3. 특정 타이머 id값을 가진 타이머 함수를 종료시킨다. => clearInterval(timerid)

 참고 http://egloos.zum.com/newkong/v/4088409

 

1. 특정시간마다 특정함수를 호출/실행, setInterval 함수


 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        #output {
            width: 200px;
            height: 200px;
            border: 4px solid #000;
            margin: 50px;
 
            font-size: 100px;
            text-align: center;
            line-height: 200px;
            vertical-align: middle;
 
        }
    </style>
    <script src="../../libs/jquery-1.11.0.min.js"></script>
 
    <script>
        // 예제01: 1초에 한 번씩 변수 값을 1씩 증가시키고 이 값을 #output 영역에 출력해 주세요.
        $(document).ready(function () {
 
            var $output = $("#output");
            var count = 0;
 
            // 여기에 풀이를 입력해주세요.
            // 함수 생성
            function addCount() {
                // 값 증가
                count++;
                // 값을 출력
                $output.text(count);
            }
 
            addCount();
            setInterval(addCount, 1000);
 
        })
 
    </script>
 
 
</head>
 
<body>
<div id="output">
    0
</div>
</body>
</html>
 
cs

 

이 코드는 1초 마다 숫자를 1씩 증가시켜주는 코드입니다. 딱히 어렵지 않은 코드라고 생각합니다. 여기서 하나 알아야 할 것은 setInterval 함수가 어떠한 리턴 값 없이 매개변수안에 있는 실행구문을 실행시켜주고 끝이 아닙니다. setInterval 함수는 코드내 유일한 timer id를 int 형태로 반환하는 함수입니다. (timer id값은 clearInterval 함수로 타이머 함수를 종료시킬 때 사용 될수 있는 유니크 키 값이라고 생각해도 좋습니다.)

 


 

2. 특정시간 이후에 딱 한번만 함수 호출/실행 , setTimeOunt 함수


 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        #output {
            width: 600px;
            height: 200px;
            border: 4px solid #000;
            margin: 50px;
 
 
            text-align: center;
            line-height: 200px;
            vertical-align: middle;
 
        }
    </style>
    <script src="../../libs/jquery-1.11.0.min.js"></script>
 
    <script>
        // 예제02: 3초 후에 “안녕하세요. 환영합니다.” 메시지를 화면에 출력해 주세요.
        $(document).ready(function () {
 
            var $output = $("#output");
 
            // 여기에 풀이를 입력해주세요.
            setTimeout(function () {
                $output.text("안녕하세요. 환영합니다.")
            }, 3000);
 
        })
 
    </script>
 
 
</head>
 
<body>
<div id="output">
 
</div>
</body>
</html>
 
cs
이 코드는 3초 후에 매개변수 안에 있는 익명함수를 호출하여 "안녕하세요. 환영합니다"라는 메시지를 $("#output") 안에 출력하는 기능을 딱 한번만 실행시켜주는 코드입니다.
 

 

3. 특정 타이머 함수를 종료시켜주는 함수 , clearInterval 함수


 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        #output {
            width: 200px;
            height: 200px;
            border: 4px solid #000;
            margin: 50px;
 
            font-size: 100px;
            text-align: center;
            line-height: 200px;
            vertical-align: middle;
 
        }
    </style>
    <script src="../../libs/jquery-1.11.0.min.js"></script>
 
    <script>
        /*
         예제 03: 1초에 한번씩 숫자 값 출력하기
         변수 값을 1초에 한 번 1씩 증가시키고 이 값을 화면에 출력해 주세요.
         단, 정지버튼(#stip)을 누르면 더 이상 실행되지 않게 타이머 함수를 중지시켜 주세요.
 
         */
        $(document).ready(function() {
 
            var $output = $("#output");
            var count = 0;
            var timerID=0;
            timerID = setInterval(function() {
                // 값 증가
                count++;
                // 값을 출력
                $output.text(count);
            }, 1000);
 
 
            $("#stop").click(function() {
                // 여기에 풀이를 입력해주세요.
                clearInterval(timerID);
            });
 
        })
 
    </script>
 
 
</head>
 
<body>
<button id="stop">멈춤</button>
<div id="output">
    0
</div>
</body>
</html>
 
cs

 

이 코드는 setInterval 함수에 의해서 1초마다 1씩 증가되는 값을 출력시켜주는 타이머 함수를 종료시켜주는 코드입니다. 여기에 쓰이는 함수가 clearInterval 함수입니다. 여기서 보이는 것은 setInterval 함수의 리턴 값을 timerID라는 변수에 담아주고 이 변수를 이용해 clearInterval 함수를 사용하여 특정타이머를 종료시켜줍니다. 

 

 

 

 
출처: http://blog.pages.kr/29 좋은 자료들 많이 있다.

1. setTimeout() 메소드 - 일정시간후 코드실행  > setTimeout(code, delay);  code : 일정시간 후 실행시킬 자바스크립트 코드를 포함한 문자열(함수나 alert같은 코드들...)
  delay : 문자열 code 내에 있는 자바스크립트 코드가 실행되기까지 걸리는 시간 (1/1000초 단위)

 

2. setInterval() 메소드 - 일정시간후 코드 반복실행  > setInterval(code, delay);  setTimeout()과 같이 일정시간후에 코드가 실행되지만, 한번실행이 아닌 반복실행된다. 

code : 일정시간 후 실행시킬 자바스크립트 코드를 포함한 문자열(함수나 alert같은 코드들...)

 delay : 문자열 code 내에 있는 자바 크립트 코드가 실행되기까지 걸리는 시간 (1/1000초 단위)

 

3. clearInterval() 메소드 - clearInterval로 setInterval함수로 정해진 반복코드를 멈추게한다.  > clearInterval("setInterval로 생성된 변수")  code : 일정시간 후 실행시킬 자바스크립트 코드를 포함한 문자열(함수나 alert같은 코드들...)
  delay : 문자열 code 내에 있는 자바스크립트 코드가 실행되기까지 걸리는 시간 (1/1000초 단위)
  ex) var intA = setInterval("clock()",50)  // 0.05초마다 clock()함수를 실행한다.
      clearInterval(intA) //setInterval()로 실행된 메소드를 취소한다.

 

 

 

 

 

[ JavaScript ] 일회용 타이머 setTimeout() 메소드

1. setTimeout(함수명, 시간) - '함수명'이라고 되어있는 부분에 일정 시간 뒤에 실행시키고 싶은 함수나 명령 따위를 넣는다. - 주의할 것은, function01() 이라는 함수를 사용한다 할때, setTimeout(function,

egloos.zum.com

 

[ JavaScript ] 일회용 타이머 setTimeout() 메소드

1. setTimeout(함수명, 시간) - '함수명'이라고 되어있는 부분에 일정 시간 뒤에 실행시키고 싶은 함수나 명령 따위를 넣는다. - 주의할 것은, function01() 이라는 함수를 사용한다 할때, setTimeout(function,

egloos.zum.com

 

 

Posted by useways
,