레이블이 javascript인 게시물을 표시합니다. 모든 게시물 표시
레이블이 javascript인 게시물을 표시합니다. 모든 게시물 표시

2009년 10월 25일 일요일

input type=radio context 관련

context 두개를 함께 쓰는것도 가능함

 

이름을 찾고 값을 찾아서 해당 값을 선택하게 할 수 있다.

$("input[name=r" + obj.list[i].seq + "][value=" + obj.list[i].value + "]").attr("checked","checked");  

이 글은 스프링노트에서 작성되었습니다.

2009년 8월 4일 화요일

stript tab from string

  1. var htstring = '<p align="Left"><b>Hello</b> <I>World</I></p>';
    var stripped = htstring.replace(/(<([^>]+)>)/ig,"");

 

간혹 javascript내의 string의 html tag를 삭제 하고 싶을때가 있다.

이 글은 스프링노트에서 작성되었습니다.

2009년 7월 30일 목요일

javascript foreach

// stock_tx
// js foreach
for (var i in obj['stock_tx'])
{

    // i에 key값이 오는거야 ~~ 가는거야..
    row = obj['stock_tx'][i];
    $("#detail #stock_tx").append('<div>' + row['crdate'] + '</div>');
}

 

 

 

 

           

 

 

이 글은 스프링노트에서 작성되었습니다.

2009년 7월 21일 화요일

jquery block UI 사용 예제

  1. <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.blockUI.js"></script>
  2. <script>
  3. function block()

  4. {

  5. $.blockUI({message:$("#block_layer"),fadeIn:false});

  6. }

  7. functino unblock()

  8. {

  9.      $.unblockUI({fadeOut:false});

  10. }

  11.  </script>
  12.  
  13. <div id="block_layer">
  14.     <div>download</div>
  15. </div>

 

이 글은 스프링노트에서 작성되었습니다.

2009년 7월 10일 금요일

페이지별 화면 출력

적은 내용을 여러 페이지에 하고싶을 때가 있다.

<html>
<head>
<title>Sample Printing</title>
<style>P.page{page-break-after: always}</style>
</head>
<body>
<p class=page>
this is a page printing sample.after the end of 
this p tag printing will start from next page.
</p>
<p class=page>
See it will print the data from next page.
Here we will give a button using that button 
we will print this document.
<br>
<input type=button name=printit value='Print Me' onClick='print();'>
</p>
</body>
</html>

2009년 6월 8일 월요일

jquery opener 컨트롤

팝업창에서 부모창에 값 셋팅하기.
$(opener.document).find('#id_of_dom_element')

$(opener.document).find(':radio').each( function(){
    if( $(this).val() == "2" ) $(this).attr('checked', 'checked');
});

2009년 5월 20일 수요일

마우스 포지션 트래킹

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
   $().mousemove(function(e){
      $('#status').html(e.pageX +', '+ e.pageY);
   });
})
</script>
<body>
<h2 id="status">
0, 0
</h2>
</body>
</html>

2009년 5월 14일 목요일

숫자 3자리 마다 , 넣는 function

 function t_format(nNum){
        var sNum = "";
        var len= 0;
        do{
            sNum = nNum % 10 + ((len++ % 3 == 0 && len > 1)?",":"") + sNum;
        }while( (nNum = Math.floor(nNum / 10)) > 0)
       
        return sNum;        
    }

2008년 11월 21일 금요일

jquery] dimension plugin사용.. position, width, height, scrolltop

http://brandonaaron.net/docs/dimensions/#api

window 객체의 offset등을 알기위해 plugin설치

<script type=text/javascript src='js/jquery.dimensions.min.js'></script>

윈도 width
$(window).width()

객제 width
$("#obj").width()

윈도 스크롤
$(window).scrollTop()

지원하는 function list
 *  height
    * innerHeight
    * innerWidth
    * offset
    * offsetParent
    * outerHeight
    * outerWidth
    * position
    * scrollLeft
    * scrollTop
    * width

2008년 11월 19일 수요일

[jquery] radio button context

radio button도 checkbox와 마찬가지의 context를 사용한다 다만...id를 가지고 handling을 하게 되면..휑~~~

<input type=radio name=r1 id='r1' value=1>
<input type=radio name=r1 id='r1' value=2>
<input type=radio name=r1 id='r1' value=3>

$("#r1:selected").val()

이런식으로 하면 2번째 radio button이 selected될 경우 undefined 오류가 발생할 수 있다.
어쩔 수 없이 class를 사용해야 함

<input type=radio name=r1 class='r1' value=1>
<input type=radio name=r1 class='r1' value=2 selected>
<input type=radio name=r1 class='r1' value=3>

$(".r1:selected").val()


2008년 11월 13일 목요일

javascript str replace 샘플

str.replace(/,/g,'') => 매칭 되는 전체를 바꿀 경우
str.replace(',','') => 하나 밖에 안 바뀜

2008년 10월 17일 금요일

javascript logger blackbird 이것으로 소스에 alter걸며 디버깅 하던것이 끝이 나려나?

http://www.gscottolson.com/blackbirdjs/

logger를 설치하면 좌측 상단에 패널이 하나 생기고 로그들이 기록될 것이다....
사용자 삽입 이미지


step 1. 사이트에서 파일을 내려 받았다.
blackbird.css와 blackbird.js가 필요한 것 같다
압축을 풀어놓은 화면
사용자 삽입 이미지

step 2. ftp로 파일 전송
이미지 파일이 두개가 있는데 어디다 넣으면 좋을지 모르겠군
일단은 하나의 디렉터리에 모두 전송

step 3. sample 작성
<!-- begin of debug lib -->
<script type="text/javascript" src="/js/blackbird.js"></script>
<link type="text/css" rel="Stylesheet" href="/js/blackbird.css" />
<!-- end of debug lib -->




keyboard로도 control가능함
멋짐
사용자 삽입 이미지


오류나고 되지도 않음...아침부터 짜증남...



2008년 8월 19일 화요일

nhn에서 제공하는 xml 파서

/**
 * @projectDescription Jindo Json Extend
 * @copyright NHN corp. <http://www.nhncorp.com>
 * @author AjaxUI Team (gony)
 * @version 0.1
 * @since 0.2.9 <jindo.do.js>
 */

var JINDO = new Object();
JINDO.xml2obj = function(xml) 
{
	var obj = {}, que = [], depth = 0;

	// attribute를 해석하기 위한 함수	
	var parse_attr = function(oobj, str) {
		str.replace(/([^=\s]+)\s*=\s*"([^"]*)"/g, function(a0,a1,a2) {
			oobj[a1] = a2;
		});
	}
	
	// 주석, XML선언, 태그 사이 공백 등의 의미 없는 코드를 삭제
	xml = xml.replace(/<(\?|\!-)[^>]*>/g,'').replace(/>\s+</g, '><');
	
	// 하위 노드가 없는 태그는 하나의 닫힌 태그로 수정
	xml = xml.replace(/<([^!][^ >]+)(\s[^>]*)?><\/\1>/g, '<$1$2 />').replace(/^\s+|\s+$/g, '');

	// 함수 객체를 정규 표현식 처리의 인자로 줘서 iterator로 사용
	xml = xml.replace(/<\/?([^\!][^ >]*)(\s[^>]*)?>(<\/$1>|<\!\[CDATA\[(?:(.|\s)*?)\]\]>|[^<>]*)/g, function(a0,a1,a2,a3)
	{
		// IE에서 일치하는 내용이 없으면 undefined로 전달되므로
		// 빈 문자열로 변경해 다른 브라우저와의 호환성을 맞춤
		if (typeof a1 == 'undefined') a1 = '';
		if (typeof a2 == 'undefined') a2 = '';
		if (typeof a3 == 'undefined') a3 = '';
		
		if (a0.substr(1,1) == '/') { // 현재 태그가 닫는 태그라면,
			// 깊이를 1만큼 감소 
			depth--;
		} else if (que.length == 0) { // 객체 큐에 객체가 없다면,
			que[depth] = obj; // 초기의 객체를 큐에 넣고
			parse_attr(obj, a2); // attribute를 해석
		} else {
			var k  = a1, o = {}, is_closed = false;
			
			is_closed = (a2.substr(-1,1) == '/');
			if (a3.length > 0 || is_closed) { // 텍스트 노드가 있다면
				o = a3; // 추가할 객체는 문자열 객체
				
				// CDATA라면 전달받은 그대로 리턴하고
				// 그렇지 않다면 decode 해서 리턴
				if (o.substr(0,9) == '<![CDATA[' && o.substr(-3,3) == ']]>') o = o.substring(9, o.length-3);
				else o = o.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
			}
			
			// 객체를 할당하기 전에 태그 이름이 이미 존재하는지 살펴보고
			// 이전에 존재하는 태그라면, 배열로 만든다. 이미 배열이라면 현재의 객체를 배열에 추가
			if (typeof que[depth][k] == 'undefined') {
				que[depth][k] = o;
			} else {				
				var v = que[depth][k];
				if (que[depth][k].constructor != Array) que[depth][k] = [v];
				que[depth][k].push(o);
			}

			// attribute를 해석
			parse_attr(o, a2);
			
			if (!is_closed) que[++depth] = o;	
		}
		
		return '';
	});
	
	return obj;
}

2008년 7월 28일 월요일

javascript에서 xml string을 control

// 1. dom document component 생성
xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");

// 2. xml문서 양식의 data를 loadXML을 사용해 load
xmldoc.loadXML( data );
       
// 3. 출력 샘플
alert ( "평균입고:" + xmldoc.getElementsByTagName("dataset")[4].getAttribute("tot_stockin") + "\n평균출고:" + xmldoc.getElementsByTagName("dataset")[4].getAttribute("tot_deliv") );

2008년 4월 3일 목요일

array concat 를 사용하다...array를 결합

<script type="text/javascript">

var arr = new Array(3);
arr[0] = "Jani";
arr[1] = "Tove";
arr[2] = "Hege";

var arr2 = new Array(3);
arr2[0] = "John";
arr2[1] = "Andy";
arr2[2] = "Wendy";

document.write(arr.concat(arr2));

</script>

json에서 사용한다면
var objJson = new object();
objJson.list = [1,2,3,4];

라고 하면 아래와 같은 구조로 만들어 질 것 같다.
objJson = { list:[1,2,3] } 이라고 가정하고

objJson.list.concat( arr2 ) 정도이면 될까?

여러개의 언어를 동시에 사용하다 보니..헛갈리네. 나참 다들 비슷해서리..

Array에 관한 테스트라고나 할까?

json을 준비 중..

<script language=javascript>
var a = new Array();
var b = new Object();
b.name = 'haha';

var c = new Object();
c.name = 'hoho';

a[0] = b;
a.push(c);

document.write( a[1].name );

</script>

test


push도 있고 slice도 있고 다 있구만, 내가 그전에도 이런걸 사용했었나?

[json] Json 방식으로 Ajax request

먼저 json방식의 자료를 만들어야겠다.

array일 경우
var Beatles = ["Paul","John","George","Ringo"];
var Beatles = new Array("Paul","John","George","Ringo");

Object일 경우
var Beatles = {
     "Country" : "England",
     "YearFormed" : 1959,
     "Style" : "Rock'n'Roll"
}

아래의 경우는 위와 동일함
var Beatles = new Object();
Beatles.Country = "England";
Beatles.YearFormed = 1959;
Beatles.Style = "Rock'n'Roll";

Object 출력
alert(Beatles.Style); //Dot Notation
alert(Beatles["Style"]); //Bracket Notation


Array를 Object에 사용할 경우
var Beatles = {
     "Country" : "England",
     "YearFormed" : 1959,
     "Style" : "Rock'n'Roll",
     "Members" : ["Paul","John","George","Ringo"]
}


Array내부에 Object사용
var Rockbands = [
     {
         "Name" : "Beatles",
         "Country" : "England",
         "YearFormed" : 1959,
         "Style" : "Rock'n'Roll",
         "Members" : ["Paul","John","George","Ringo"]
     }
,
    {
        "Name" : "Rolling Stones",
        "Country" : "England",
        "YearFormed" : 1962,
        "Style" : "Rock'n'Roll",
         "Members" : ["Mick","Keith","Charlie","Bill"]
      }

]

Json Syntax
Javascript Object 와 흡사함

{
"Name" : "Beatles",
"Country" : "England",
"YearFormed" : 1959,
"Style" : "Rock'n'Roll",
"Members" : ["Paul","John","George","Ringo"]
}

내가 원하는것은 만들어진 Json을 어떻게 Ajax를 사용해 전송 할 것인가? 하는 것이다.
그 전에 Json Parser란게 필요하다.
사실 eval( ) 을 사용해서 parsing을 하고 있었는데 parser를 쓰면 더 좋단다. 흠흠..

http://www.json.org/json.js

  • JSON.parse(strJSON) - converts a JSON string into a JavaScript object.
  • JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.
  • 순서는 다음과 같다.
    Client Side
    1. Json을 만든다.
    2. Json파서를 사용해 stringify() 작업을 한다. 이건 object를 string으로 만들어 버리겠다는것?
    3. Send the URL-encoded JSON string to the server as part of the HTTP Request

    Sample:

    var objJSON = {
       "msg" : MSG
      };
      var strJSON = encodeURIComponent(JSON.stringify(objJSON));
      new Ajax.Request("ReceiveJSON.jsp",
       {
        method: "post",
        parameters: "strJSON=" + strJSON,
        onComplete: Respond
       });


    Server Side(php)
    strJSON 파라미터를 받아서 json_decode() 하게 되면 array의 형식으로 변경됨.
    알아서 작업하면 됨....

    -------------------------
    헌데 분명
    Content_Type     => 'application/json',
    Content              => $json_req,
    의 방법을 이용한 경우가 있는데 이럴때는 서버측에서 어떻게 해야 하나?





     



    2008년 3월 22일 토요일

    keydown event 처리

    document.onkeydown = keypressed;

    function keypressed()
    {
       if (event.keyCode == 13)
           check_submit();
    }

    // javascript에서 enter키를 칠 경우 check_submit을 실행함

    2008년 3월 1일 토요일

    [oop] 기존 속성에 새로운 메서드 추가

    prototype 속성 사용한다.

    Number.prototype.toHexString = function(){
                                              return this.toString(16);
                                           };
    function builtTest()
    {
       var a = 15;
       alert(a.toHexString());
    }