JS 2011. 9. 1. 09:35
http://yuilibrary.com/download/yuicompressor/
http://phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=60412
http://yui.2clics.net/
http://phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=52074

yuicompressor-2.4.6.zip


posted by 나는너의힘
:
JS 2011. 8. 25. 18:05
http://www.microsoft.com/download/en/confirmation.aspx?id=18359

IEDevToolBarSetup.msi

JSLeaksDetector.msi


posted by 나는너의힘
:
JS 2011. 8. 25. 14:52
http://msdn.microsoft.com/en-us/library/Bb250448.aspx


Justin Rogers
Microsoft Corporation

June 2005

The Evolution of the Web Developer

In the past, memory leaks haven't posed huge problems for Web developers. Pages were kept relatively simple and navigation between different locations within a site was a great way to clean up any loose memory. If there was a leak, it was most likely small enough to go unnoticed.

New Web applications live up to higher standards. A page might run for hours without being navigated and retrieve updated information dynamically through Web services. Language features are pushed to the breaking point by combining complex event schemes, object-oriented JScript, and closures to produce entire applications. With these and other changes, certain memory leak patterns are becoming more prominent, especially those previously hidden by navigation.

The good news is that memory leak patterns can be easily spotted if you know what to look for. Most of the troublesome patterns you might face have known workarounds requiring only a small amount of extra work on your behalf. While some pages might still fall prey to small memory leaks, the most noticeable ones can be easily removed.

Leak Patterns

The following sections will discuss patterns of memory leaks and point out some common examples of each pattern. One great example of a pattern is the closure feature of JScript, while another example is the use of closures in hooking events. If you're familiar with the event hooking example, you might be able to find and fix many of your memory leaks, but other closure-related issues might go unnoticed.

Now, let's look at the following patterns:

  1. Circular References—When mutual references are counted between Internet Explorer's COM infrastructure and any scripting engine, objects can leak memory. This is the broadest pattern.

  2. Closures—Closures are a specific form of circular reference that pose the largest pattern to existing Web application architectures. Closures are easy to spot because they rely on a specific language keyword and can be searched for generically.

  3. Cross-Page Leaks—Cross-page leaks are often very small leaks of internal book-keeping objects as you move from site to site. We'll examine the DOM Insertion Order issue, along with a workaround that shows how small changes to your code can prevent the creation of these book-keeping objects.

  4. Pseudo-Leaks—These aren't really leaks, but can be extremely annoying if you don't understand where your memory is going. We'll examine the script element rewriting and how it appears to leak quite a bit of memory, when it is really performing as required.

Circular References

Circular references are the root of nearly every leak. Normally, script engines handle circular references through their garbage collectors, but certain unknowns can prevent their heuristics from working properly. The unknown in the case of IE would be the status of any DOM elements that a portion of script has access to. The basic principle would be as follows:




Figure 1. Basic Circular Reference Pattern

The cause of the leak in this pattern is based on COM reference counting. The script engine objects will hold a reference to the DOM element and will be waiting for any outstanding references to be removed before cleaning up and releasing the DOM element pointer. In our case we have two references on the script engine object: the script engine scope, and the DOM element expando property. While terminating the script engine will release the first reference, the DOM element reference will never be released because it is waiting on the script engine object to release it! You might think it would be easy to detect this scenario and fix the problem, but in practice the basic case presented is only the tip of the iceberg. You could have circular references at the end of a 30 object chain and those would be much harder to detect.

If you are wondering what this pattern looks like in HTML, you can cause a leak by using a global script engine variable and a DOM element as shown.

<html>
    <head>
        <script language="JScript">

        var myGlobalObject;

        function SetupLeak()
        {
            // First set up the script scope to element reference
            myGlobalObject =
                document.getElementById("LeakedDiv");

            // Next set up the element to script scope reference
            document.getElementById("LeakedDiv").expandoProperty =
                myGlobalObject;
        }


        function BreakLeak()
        {
            document.getElementById("LeakedDiv").expandoProperty =
                null;
        }
        </script>
    </head>

    <body onload="SetupLeak()" onunload="BreakLeak()">
        <div id="LeakedDiv"></div>
    </body>
</html>

To break the leak pattern you can make use of explicit null assignments. By assigning null before the document unloads you are telling the script engine there is no longer an association between the element and the object inside the engine. It can now properly clean up references and will release the DOM element. In this case, you as the Web developer know more about the relationships between your objects than the script engine does.

While that is the basic pattern, it can be difficult to spot more complex scenarios. A common usage of object-oriented JScript is to extend DOM elements by encapsulating them inside of a JScript object. During the construction process, you generally pass in the DOM element you want to attach to and then store a reference to the DOM element on the newly constructed object while at the same time storing an instance of the newly constructed object on the DOM element. That way your application model always has access to everything it needs. The problem is this is a very explicit circular reference, but because it uses different language aspects it might go unnoticed. Breaking up this kind of pattern can become more complex, and you can use the same simple methods discussed earlier.

<html>
    <head>
        <script language="JScript">

        function Encapsulator(element)
        {
            // Set up our element
            this.elementReference = element;

            // Make our circular reference
            element.expandoProperty = this;
        }

        function SetupLeak()
        {
            // The leak happens all at once
            new Encapsulator(document.getElementById("LeakedDiv"));
        }

        function BreakLeak()
        {
            document.getElementById("LeakedDiv").expandoProperty =
                null;
        }
        </script>
    </head>

    <body onload="SetupLeak()" onunload="BreakLeak()">
        <div id="LeakedDiv"></div>
    </body>
</html>

More complex solutions to this problem involve registration schemes to note which elements/properties need to be unhooked, having the peer element hook events so that it can clean up before the document unloads, but often you can run into additional leak patterns without actually fixing the problem.

Closures

Closures are very often responsible for leaks because they create circular references without the programmer being fully aware. It isn't immediately obvious that parent function parameters and local variables will be frozen in time, referenced, and held until the closure itself is released. In fact this has become such a common programming tactic, and users have run into issues so often, there are quite a few resources already available. Because they detail some of the history behind closures as well as some of the specific instances of closure leaks we'll check those out after applying the closure model to our circular reference diagram and figuring out where these extra references are coming from.



Figure 2. Circular References with Closures

With normal circular references there were two solid objects holding references to each other, but closures are different. Rather than make the references directly, they are made instead by importing information from their parent function's scope. Normally, a function's local variables and the parameters used when calling a function only exist for the lifetime of the function itself. With closures, these variables and parameters continue to have an outstanding reference as long as the closure is alive, and since closures can live beyond the lifetime of their parent function so can any of the locals and parameters in that function. In the example, Parameter 1 would normally be released as soon as the function call was over. Because we've added a closure, a second reference is made, and that second reference won't be released until the closure is also released. If you happened to attach the closure to an event, then you would have to detach it from that event. If you happened to attach the closure to an expando then you would need to null that expando.

Closures are also created per call, so calling this function twice will create two individual closures, each holding references to the parameters passed in each time. Because of this transparent nature it is really easy to leak closures. The following example provides the most basic of leaks using closures:

<html>
    <head>
        <script language="JScript">

        function AttachEvents(element)
        {
            // This structure causes element to ref ClickEventHandler
            element.attachEvent("onclick", ClickEventHandler);

            function ClickEventHandler()
            {
                // This closure refs element
            }
        }

        function SetupLeak()
        {
            // The leak happens all at once
            AttachEvents(document.getElementById("LeakedDiv"));
        }

        function BreakLeak()
        {
        }
        </script>
    </head\>

    <body onload="SetupLeak()" onunload="BreakLeak()">
        <div id="LeakedDiv"></div>
    </body>
</html>

If you are wondering how to break this leak, it won't be as easy as a normal circular reference. The "closure" can be viewed as a temporary object that exists in the function scope. Once the function exits, you lose reference to the closure itself, so what would you end up calling detachEvent with? One of the most interesting approaches to this problem was demonstrated on MSN spaces thanks to Scott Isaacs. The approach uses a second closure to additionally hook the window's onUnload event, and because this closure has the same "scoped" objects it is able to detach the event, detach itself, and finish the clean up process. To make everything easily fit with our model we can also store the closure on an expando, detach it, and then null the expando, as in the following example.

<html>
    <head>
        <script language="JScript">

        function AttachEvents(element)
        {
            // In order to remove this we need to put
            // it somewhere. Creates another ref
            element.expandoClick = ClickEventHandler;

            // This structure causes element to ref ClickEventHandler
            element.attachEvent("onclick", element.expandoClick);

            function ClickEventHandler()
            {
                // This closure refs element
            }
        }

        function SetupLeak()
        {
            // The leak happens all at once
            AttachEvents(document.getElementById("LeakedDiv"));
        }

        function BreakLeak()
        {
            document.getElementById("LeakedDiv").detachEvent("onclick",
                document.getElementById("LeakedDiv").expandoClick);
            document.getElementById("LeakedDiv").expandoClick = null;
        }
        </script>
    </head>

    <body onload="SetupLeak()" onunload="BreakLeak()">
        <div id="LeakedDiv"></div>
    </body>
</html>

In a Knowledge Base article, we actually recommend that you try not to use closures unless they are necessary. In the example, I've given we don't need to use a closure as the event handler, instead we can move the closure to a global scope. When the closure becomes a function, it no longer inherits the parameters or local variables from its parent function so we don't have to worry about closure-based circular references at all. Most code can be fixed by creating an architecture that doesn't rely on closures where they aren't necessary.

Finally, Eric Lippert, one of the developers of the scripting engines, has a great post on closures in general. His final recommendations are also along the lines of only using closures when truly necessary. While his article doesn't mention any of the workarounds for the closure pattern, hopefully we've covered enough examples here to get you started.

Cross-Page Leaks

Leaks that are based on order of insertion are almost always caused by the creation of intermediate objects that don't get cleaned up properly. That is exactly the case when creating dynamic elements and then attaching them to the DOM. The basic pattern is attaching two dynamically created objects together temporarily which creates a scope from the child to the parent element. Later, when you attach this two-element tree to the primary tree, they both inherit the scope of the document and a temporary object is leaked. The following diagram shows two methods for attaching dynamically created elements to the tree. In the first model, attach each child element to its parent, and finally attach the entire subtree to the primary tree. This method can cause leaks through temporary objects if other conditions are met. In the second model, we attach elements into the primary tree working our way from top-level dynamically created element down through all of the children. Because each attachment inherits the scope of the primary document we never generate temporary scopes. This method is much better at avoiding potential memory leaks.




Figure 3. DOM Insertion Order Leak Model

Next, we are going to cover an example of a leak that is transparent to most leak-detection algorithms. Because we don't leak any publicly visible elements and the objects we leak are very small you might never notice this problem. For our example to work, the dynamically created elements will have to contain a script pointer in the form of an inline function. This will allow us to leak an internal script object that is created temporarily as we attach elements together. Because the leak is small, we'll have to run thousands of samples. In fact, the objects leaked are only a few bytes. By running the sample and navigating to an empty page, you can see the difference in memory consumption between the two versions. When we use the first DOM model of attaching child to parent, then parent to the primary tree, our memory usage goes up a bit. This is a cross-navigation leak and the memory isn't reclaimed until you restart the IE process. If you run the sample a few more times, using the second DOM model of attaching the parent to the primary tree and then the child to the parent, your memory won't continue to climb and you'll find that you've fixed the cross-page navigation leak.

<html>
    <head>
        <script language="JScript">

        function LeakMemory()
        {
            var hostElement = document.getElementById("hostElement");

            // Do it a lot, look at Task Manager for memory response

            for(i = 0; i < 5000; i++)
            {
                var parentDiv =
                    document.createElement("<div onClick='foo()'>");
                var childDiv =
                    document.createElement("<div onClick='foo()'>");

                // This will leak a temporary object
                parentDiv.appendChild(childDiv);
                hostElement.appendChild(parentDiv);
                hostElement.removeChild(parentDiv);
                parentDiv.removeChild(childDiv);
                parentDiv = null;
                childDiv = null;
            }
            hostElement = null;
        }


        function CleanMemory()
        {
            var hostElement = document.getElementById("hostElement");

            // Do it a lot, look at Task Manager for memory response

            for(i = 0; i < 5000; i++)
            {
                var parentDiv =
                    document.createElement("<div onClick='foo()'>");
                var childDiv =
                    document.createElement("<div onClick='foo()'>");

                // Changing the order is important, this won't leak
                hostElement.appendChild(parentDiv);
                parentDiv.appendChild(childDiv);
                hostElement.removeChild(parentDiv);
                parentDiv.removeChild(childDiv);
                parentDiv = null;
                childDiv = null;
            }
            hostElement = null;
        }
        </script>
    </head>

    <body>
        <button onclick="LeakMemory()">Memory Leaking Insert</button>
        <button onclick="CleanMemory()">Clean Insert</button>
        <div id="hostElement"></div>
    </body>
</html>

This leak deserves clarification, because our workaround goes against some best practices in IE. The key points to understand about the leak are that DOM elements are being created with scripts already attached. This is actually crucial to the leak, because if we create DOM elements that don't contain any script and attach them together in the same manner we don't have a leak problem. This gives rise to a second workaround that might be even better for larger subtrees (in the example we only have two elements, so building the tree off the primary DOM isn't a performance hit). The second workaround would be to create your elements with no scripts attached initially so that you can safely build your subtree. After you've attached your subtree to the primary DOM, go back and wire up any script events at that point. Remember to follow the principles for circular references and closures so you don't cause a different leak in your code as you hook up your events.

I really wanted to point out this issue because it shows that not all memory leaks are easy to find. It could take thousands of iterations of a smaller pattern to become visible, and it might be something slight, like the order of insertion of DOM elements that causes the problem to arise. If you tend to program using only best practices, then you think you are safe, but this leak shows that even best practices can exhibit leaks. Our solution here was to improve upon the best practice or even introduce a new best practice in order to remove the leaking condition.

Pseudo-Leaks

Often times the actual behavior and expected behavior of some APIs can lead you to misdiagnose memory leaks. Pseudo-leaks almost always appear on the same page during dynamic scripting operations and should rarely be visible after navigation away from the page to a blank page. That is how you can eliminate the issue as a cross-page leak and then start to work on whether the memory consumption is expected. We'll use script text rewriting as our example of a pseudo-leak.

Like the DOM Insertion Order issue, this issue also relies on the creation of temporary objects in order to "leak" memory. By rewriting the script text inside of a script element over and over again, slowly you'll begin to leak various script engine objects that were attached to the previous contents. In particular, objects related to debugging script are left behind as are fully formed code elements.

<html>
    <head>
        <script language="JScript">

        function LeakMemory()
        {
            // Do it a lot, look at Task Manager for memory response

            for(i = 0; i < 5000; i++)
            {
                hostElement.text = "function foo() { }";
            }
        }
        </script>
    </head>

    <body>
        <button onclick="LeakMemory()">Memory Leaking Insert</button>
        <script id="hostElement">function foo() { }</script>
    </body>
</html>

If you run the above code and use the Task Manager trick again, while navigating between the "leaking" page and a blank page, you won't notice a script leak. This script leak is entirely within a page and when you navigate away then you get your memory back. The reason this one is bad is due to expected behavior. You expect that after rewriting some script that the original script won't stay around. But it really has to, because it might have been used already for event attachments and there might be outstanding reference counts. As you can see, this is a pseudo-leak. On the surface the amount of memory consumption looks really bad, but there is a completely valid reason.

Conclusion

Every Web developer builds a personal list of code examples that they know leak and learns to work around those leaks when they see them in code. This is extremely handy and is the reason the Web is relatively leak-free today. Thinking about the leaks in terms of patterns instead of individual code examples, you can start to develop even better strategies for dealing with them. The idea is to take them into account during the design phase and make sure you have plans for any potential leaks. Use defensive coding practices and assume that you'll need to clean up all your own memory. While this is an overstatement of the problem, you very rarely need to clean up your own memory; it becomes obvious which variables and expando properties have the potential for leaking.

In the interest of patterns and design I highly recommend Scott's short blog entry because it demonstrates a general purpose example of removing all closure-based leaks. It does require a bit more code, but the practice is sound and the improved pattern is easy to spot in code and to debug. Similar registration schemes can be used for expando-based circular references as long as care is taken that the registration method itself isn't riddled with leaks (especially where closures are used)!

About the author

Justin Rogers recently joined the Internet Explorer team as an Object Model developer working on extensibility and previously worked on such notable projects as the .NET QuickStart Tutorials, .NET Terrarium, and SQL Reporting Services Management Studio in SQL Server 2005.


posted by 나는너의힘
:
JS 2011. 8. 24. 14:06
출처 : http://blog.naver.com/PostView.nhn?blogId=bg_ellder&logNo=102838476

되는지 안되는지 모름.

var obj = func.test;
........................
obj = null;  <==  참조가 끝났다면 자원을 수동으로 해제!.
 
============================================================================== 
다음은 객체의 child들 까지도 자원을 해제 할 수 있도록 하는 function 모듈입니다.
(removeChild나 insertHTML등 전에 실행하지 않도록 주의하셔요.... 당연한거겠지만..^^)
function purge(d) {
var a = d.attributes, i, l, n;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}
posted by 나는너의힘
:
JS 2011. 6. 17. 09:39
        function autoResize(i){//i 는 document 의  element(iframe)
            try {
             var st = document.getElementById("contentFrame");
             var iframeHeight= i.contentWindow.document.body.scrollHeight;
             var iframeWidth=  i.contentWindow.document.body.scrollWidth;
             (i).height=iframeWidth+20;
             (i).height=iframeHeight+20;
            } catch (e) {
             var st = document.getElementById("contentFrame");
             var iframeHeight= st.document.body.scrollHeight;
             var iframeWidth=  st.document.body.scrollWidth;
             st.height=iframeWidth+20;
             st.height=iframeHeight+20;
            }

posted by 나는너의힘
:
JS/jQuery 2010. 1. 5. 17:39
&lt;select onchange="functionname(this.options[this.selectedIndex].value)" name='newdataselect' &gt; &lt;/select&gt;
posted by 나는너의힘
:
JS 2009. 8. 26. 01:03
번역할 영어 :



<html>
  <head>
    <script type="text/javascript" src="http://www.google.com/jsapi">    </script>
    <script type="text/javascript">
    google.load("language", "1");
    function initialize() {
      var text = document.getElementById("itext").value;
   google.language.detect(text, function(result) {
   try
   {
   if (!result.error && result.language) {
     google.language.translate(text, result.language, "ko",
          function(result) {
           alert('function(result)');
           var translated = document.getElementById("translation");
           if (result.translation) {
             translated.innerHTML = result.translation;
           }
           });
   }
  
   }   catch (e)   {alert(e)  }
      });
    }
    </script>
  </head>
  <body>
    <div ><input type='text' onchange='initialize()' name='text' size='100' id='itext'/></div>
    <div id="translation"></div>
  </body>
</html>
posted by 나는너의힘
:
JS/Ajax 2009. 7. 24. 16:36

다음은 AJAX로 파일 내용을 가져오는 예제이다.

<script type="text/javascript">
var http = false;

if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}

http.open("GET", "test.txt");
http.onreadystatechange=function() {
  if(http.readyState == 4) {
    document.write(http.responseText);
  }
}
http.send(null);
</script>

text.txt 대신 URL을 넣으면 해당 URL의 내용을 가져온다.

Reference:
http://daniel.lorch.cc/docs/ajax_simple/

posted by 나는너의힘
:
JS/Ajax 2009. 7. 24. 16:04

AJAX로 다른 도메인의 데이터를 가져오려고 시도하면 오류가 발생한다.

오류 내용은 다음과 같다.

오류: 사용 권한이 없습니다.

보안 상의 이유로 AJAX를 통해 다른 도메인의 데이터를 가져올 수 없다.

하지만 우회하는 방법이 있다.

AJAX를 통해 다른 도메인의 데이터를 가져올 수 있도록 웹 브라우저의 설정을 바꿔준다.

바꾸는 방법은 다음과 같다.

도구 -> 인터넷 옵션

'보안' 탭에서 '사용자 지정 수준'을 선택한다.

'기타' -> '도메인 간의 데이터 소스 액세스'를 '사용 안함'에서 '사용'으로 변경한다.

물론 이러한 요청이 사용자에게 받아들여질리 만무하다.

차선책으로 프록시를 사용하는 방법이 있다.

동일 서버에 프록시 페이지를 생성해두고 우회하는 방법이다.

동일 서버에 프록시 페이지를 생성할 수 있는 경우에만 가능한 방법이다.

그 외에 좋은 방법을 알고 있다면,

comment plz :-)


posted by 나는너의힘
:
JS 2009. 7. 24. 11:20

출처  : http://blog.daum.net/nanhjb/5912900

아무것도 실행안되게 하기.. 엔터키쳐도 무반응

 

<input type="text" name="searchWord" value="" size="25" value=태그인넷 tagin.net
onKeyDown="javascript:if (event.keyCode == 13) window.event.returnValue = false;">

posted by 나는너의힘
:
JS 2009. 7. 22. 10:57
출처 : http://tong.nate.com/monkey82/2947064
<script>
/*
 이메일을 체크하기 위한 함수
 인수로는 element(input type=text)를 받음.
 정규 표현식 ==>
^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$
 
^[0-9a-zA-Z]                --> 첫글자는 숫자또는 영문자
[-_\.]?                           --> - 또는 _ 또는 . 이 0번 또는 1번  .은 특수문자 이므로 \. 으로
[0-9a-zA-Z]                 --> 숫자또는 영문자
([-_\.]?[0-9a-zA-Z])*@ --> @ 앞에(-,_,. 이 0~1번, 그 뒤에는 숫자,영문자)이 한번 또는 여러번
[0-9a-zA-Z]                --> @ 뒤에는 숫자 또는 영문자
[-_\.]?                          --> - 또는 _ 또는 . 이 0번 또는 1번
([-_\.]?[0-9a-zA-Z])*.   --> . 앞에(-,_,. 이 0~1번, 그 뒤에는 숫자,영문자)이 한번 또는 여러번
[a-zA-Z]{2,3}$             --> . 뒤 마지막 문자열은 영문자가 2~3개
   가능한 형식 예 : aaa@bbb.com  a7a.dd@bbbb.pe.kr.com  777_d-3@bbb.com
불가능한 형식 예 : -aaa@bbb.com  a#aa@co.kr  aaa@bbb@ccc.com  aaa@bbb.c  aaa@bbb.comp
*/
function valid_email(ele) { 
    re=/^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
   
    // 위의 조건을 만족하려면 최소 6자 이상이어야 함.
    if(ele.value.length<6 || !re.test(ele.value)) {
        alert("메일형식이 맞지 않습니다.\n 다시 입력해주세요.\n");
        ele.select();
        ele.focus();
        return false;
    } else {
        alert("제대로된 형식");
        return true;
    }
}
</script>
 
<h2>E-mail 확인</h2>
<p>
<font size=4>이메일 형식을 체크하는 정규식 입니다.</font>
<FORM name=data_form>
    Email: <INPUT TYPE=TEXT NAME=email value="">
    <input type=button value="확인" omClick="javascript:valid_email(document.data_form.email);">
</FORM>
posted by 나는너의힘
:
JS/jQuery 2009. 7. 22. 10:52

출처  : http://70003431.tistory.com/entry/jquery-radio-checked-select-option-selected

checkbox 선택된 값 가져오기

$("input[@name=rList][@checked]").val()

#######################################

http://docs.jquery.com/Attributes/val 

$('input:
checkbox[name=첵박명]:checked').val() ;

#######################################

checkbox의 value값으로 선택하기

$("input[@name=rList]").filter('input[@value='+sValue+']').attr("checked", "checked");

 

select box 선택된 값 가져오기
$("#ddl > option:selected").val();

select box의 value값으로 선택하기

$("#ddl > option[@value="+sValue+"]").attr("selected", "true");



출처 : http://cspark.egloos.com/2181832
radio 부분

jQuery에서 제공해주는 정의 필터 셀렉터를 사용해서 radio버튼의 value값을 가져오는 방식은 아래와 같다.

  $(":input:radio[name=sample]:checked").val()

<input type="radio" name ="sample" value="Y" checked>
<input type="radio" name ="sample" value="N">

보기엔 좀 길어보이지만 간단하게 설명된다.
최초 input 폼 엘리먼트를 선택후 radio 버튼을 가져온다음 name 속성의 값이 sample인 것중에서 선택된 값의 value를 가져온다.
위의 경우 value 값은 "Y"가 출력된다.
아무것도 선택하지 않은상태에선 value값은 'undefined'가 반환된다.

마찬가지로 radio대신 checkbox등의 체크값을 가져오는 방식도 위와 동일하다 하겠다.
posted by 나는너의힘
:
JS 2009. 7. 20. 16:07
function funcname(uid, e){
 var nv = window.navigator.appName;
 var left ;
 var top ;
 if(nv.indexOf('Microsoft')  != -1) {
  left = (event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) + 35;
  top = (event.clientY + document.body.scrollTop + document.documentElement.scrollTop) + 2;
 }else{
  left = (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) + 35;
  top = (e.clientY + document.body.scrollTop + document.documentElement.scrollTop) + 2;
 }


<a href=''  onClick='funcname("uid",event)>냥냥</a>
posted by 나는너의힘
:
JS/jQuery 2009. 7. 16. 11:59
    var left = (event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) + 35;
    var top = (event.clientY + document.body.scrollTop + document.documentElement.scrollTop) + 2;
    $.ajax({
        type: "POST",
        url: 'detail_view_2009.php',
        data: 'uid_v='+uid,
        success: function(msg){
            $(".class_dialog").css({"left":left+"px"});
            $(".class_dialog").css({"top":top+"px"});
            $(".class_dialog").fadeIn(1000);
            $(".class_dialog").show().html(msg);
        }
    });
posted by 나는너의힘
:
JS 2009. 7. 10. 21:43

출처 : http://okjsp.pe.kr/seq/68391


// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
  
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}
function encode64Han(str) {
  return encode64(escape(str))
}
function decode64Han(str) {
  return unescape(decode64(str))
}


 

posted by 나는너의힘
:
JS 2009. 7. 6. 00:38

javascript - clipboardData

 

var a = "클립보드에 복사할 내용";
window.clipboardData.setData('Text',a);

 

형식

bSuccess = object.setData(sDataFormat, sData)

a=document.body.innerText;

// body의 텍스트값만 클립보드로 복사

a=document.body.innerHTML;

// body의 HTML값까지 클립보드로 복사

 

posted by 나는너의힘
:
JS/jQuery 2009. 5. 18. 00:09
Ajax 사용하기

출처 : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax

다음은 jQuery에서 Ajax를 사용하는 예제인데 http://jquery.bassistance.de/rate.phps 페이지에 접근하여 average와 count를 가져오는 예제임.

$(document).ready(function() {
  // 마크업 생성
  $("#rating").append("Please rate: ");

  for ( var i = 1; i <=5; i++
    $("#rating").append("<a href='#'>" + i + "</a> ");

  // 마크업을 컨테이너에 추가한 후 클릭 핸들러를 적용
  $("#rating a").click( function(e) {
    // 요청 전송
    $.post("rate.php", {rating: $(this).html()}, function(xml) {
    // 출력 결과 포매팅
    $("#rating").html(
      "Thanks for rating, current average: " + $("average", xml).text() +
      ", number of votes: " + $("count", xml).text()
    );
  });
  return false;
 });
});

Ajax를 이용하여 불러오는 컨텐츠에 이벤트 핸들러를 등록할 경우 발생할 수 있는 문제는 컨텐츠가 모두 불러오지 못한 상태에서 이벤트를 등록하지 못해서 발생하는 문제인데, 이러한 문제는 함수를 위임하여 처리할 수 있음.

function addClickHandlers() {
  $("a.remote", this).click( function() {
    $("#target").load(this.href, addClickHandlers);
  });
}
$(document).ready(addClickHandlers);
posted by 나는너의힘
:
JS/jQuery 2009. 5. 18. 00:08
출처 : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

jQuery에서는 document의 ready 이벤트를 다음과 같이 등록한다.

$(document).ready(function() {
  // DOM이 준비된후 할일 정의
});

링크를 클릭했을 때 경고창으로 메시지를 띄우는 예제.
$(document).ready(function() {
  $("a").click(function() {
    alert("Hello, world!");
  });
});

$("a") 는 jQuery의 선택자(selector)이며 $는 jQuery의 클래스이므로  $()는 새로운 jQuery 객체를 생성하는 코드임. click은 jQuery 객체의 메소드로서 클릭 이벤트와 바인딩되어 이벤트 발생시 해당 메소드의 내용을 실행.
document.getElementById("orderedlist")와 같은 코드를 jQuery에서는 다음과 같이 쓸 수 있음.
$(document).ready(function() {
  $("#orderedlist").addClass("red");
});

아래는
li의 모든 child 중에서 orderedlist라는 id를 가지는 노드를 선택하여 "blue" 클래스를 추가하는 코드임.
$(document).ready(function() {
  $("#orderedlist > li").addClass("blue")
});

아래는 사용자가 리스트의 가장 마지막 li 엘리먼트위에 마우스를 갖다대었을 때 클래스를 추가하고 제거하는 코드임.
$(document).ready(function() {
  $("#orderedlist li:last").hover(function() {
    $(this).addClass("green");
  }, function() {
    $(this).removeClass("green");
  });
});

find() 메소드는 이미 선택된 엘리먼트의 자식들을 찾으며, each()는 모든 엘리먼트들을 순회하면서 주어진 작업을 수행.
$(document).ready(function() {
  $("#orderedlist").find("li").each(function(i) {
    $(this).append("  BAM! " + i);
  });
});

jQuery에서 다루고 있지 않은 메소드를 호출하고자 할 때는 다음과 같이 코드를 작성.
$(document).ready(function() {
  $("#reset").click(function() {
    $("#form")[0].reset();
  });
});

한번에 여러 폼을 reset하고자 할 때.
$(document).ready( function() {
  $("#reset").click( function() {
    $("#form").each( function() {
      this.reset();
    });
  });
});

위 경우 this는 실제적인 엘리먼트를 가리킴.

특정 그룹에서 비슷하거나 같은 엘리먼트들 중에서 특정 엘리먼트만 골라내기.
$(document).ready(function() {
  $("li").not("[ul]").css("border", "1px solid black");
});
모든 li 엘리먼트들 중에서 ul엘리먼트를 자식으로 갖지 않는 엘리먼트를 골라냄.

$(document).ready(function() {
  $("a[@name]").css("background", "#eee");
});
위 코드는 name 속성을 가지는 모든 앵커 엘리먼트에 배경색상을 추가함.

$(document).ready(function() {
  $("a[@href*=/content/gallery]").click(function() {
    // /content/gallery를 가리키는 모든 링크에서 수행할 작업
  });
});

형제 엘리먼트에 접근하여 작업 처리하기.
$(document).ready( function() {
  $("#faq").find('dd').hide().end().find('dt').click( function() {
    $(this).next().slideToggle();
  });
});

부모 엘리먼트에 접근하여 작업 처리하기.
$(document).ready( function() {
  $("a").hover( function() {
    $(this).parents("p").addClass("highlight");
  }, function() {
    $(this).parents("p").removeClass("highlight");
  });
});

다음은 $(document).ready(callback) 표기의 줄임 표현임.
$(function() {
  // DOM이 준비되었을 때 실행할 코드
});

줄임 표현을 이용하여 Hello, world! 예제를 재작성.
$( function() {
  $("a").click( function() {
    alert("Hello, world!");
  });
});
posted by 나는너의힘
:
JS/jQuery 2009. 5. 15. 00:11

 
가볍고 쉬운 Ajax - jQuery 시작하기 IT 이야기

2007/06/10 11:45

복사 http://blog.naver.com/kissin/70018447897


시작 하기 전에

 

jQuery는 2006년 초에 John Resig가 개발한 자바스크립트 라이브러리 이다. 전체 라이브러리가 55kb밖에는 안되는 초 경량이면서도 누구나 쉽게 브라우져 기반의 자바스크립트 프로그래밍을 쉽게 할 수 있을 뿐더러, Ajax또한 쉽게 구현 할 수 가 있다. 또한 플러그인 방식의 확장을 지원하여, 현재 많은 수의 플러그인을 확보하고 있다.

나온지는 얼마 안되었지만 수백여개의 사이트가 사용할 만큼 안정적이며, 유명한 라이브러리 이다. 구지 비교하자면 prototype이라는 기존 유명 라이브러리와 비교가 가능하겠지만, 더욱 간단하며, 쉽다는것을 장점으로 꼽고 있다.(사실 본인은 prototype을 잘 모른다. 따라서 기존 개발자들의 의견을 빌린것이다. 어느것이 더 좋다는 표현이 아님을 알아달라)

무엇이 짧은 시간안에 jQuery를 유명하게 하였을까? 이런 호기심을 가지고 깊이 살펴본 결과 그 이유를 알 수 있었다. 작고, 쉽고, 그러나 강력하다는 것이 그 이유이다. 따라서 이런 본인의 경험을 공유하고자 이글을 올린다.

이 글은 jQuery의 튜토리얼문서를 기반으로하여 작성 되었다. 따라서 예제의 상당 부분은 동일하다, 단, 직접 프로그래밍을 통해 소스를 돌려보고 그 경험을 글로 올리는것이니 만큼 그냥 번역 보다는 더 나을 것으로 판단 한다.

참고로 이글에서 Ajax는 비동기 통신의 경우에만 국한 하겠다. 그 이유는 jQuery에서 Ajax라는 별도 네임스페이스로 라이브러리를 지원하기 때문이다.

 

자바스크립트 전용 IDE 소개 - Aptana

 프로그래머들 중에는 IDE를 싫어하는 사람도 있다. 그러나 나는 없는것보다는 있는것이 더 낳다고 생각한다. 특히 한 언어를 위한 전용 환경을 지원할 경우는 더욱 그러하다. 브라우져 기반의 자바스크립트 프로그래밍을 하다보면 가장 어려운 점이 디버깅이다. printf디버거도 어려울 경우가 많다.(printf디버거는 디버깅을 위해 필요한 값을 출력하여 확인 하는 방법을 말한다.-본인이 만들어낸 용어이다.) 특히 브라우져의 경우는 로컬파일을 사용할 수 없어 화면을 이용한 값의 출력에 의존하여야 함으로 루프값을 출력할 경우는 거의 죽음이고, HTML태그를 생성하여 이곳에 이벤트를 결합하고, 코딩하는것을 반복하는 동적 HTML프로그래밍은 더욱 디버깅이 어렵다. 따라서 브라우져의 플러그인과 결합된 디버거를 사용하는것이 매우 도움이 된다.

Firefox용 Firebug가 대표적인 것인데, 가장 많이 사용하는 디버거 이기도 하다. 그러나 편집기와 독립된 형태로 사용해야 함으로 수정 작업 시 불편함이 따른다. 이러한 점을 개선하려면 역시 디버거와 편집기를 포함하는 전용 IDE가 필요하다.

한가지더 이야기 하면, 기존 Eclipse와 같은 IDE에서 지원하는 Code Inspector기능의 필요를 들 수 있다. 사실 한 언어에 익숙한 사람이면 이 기능이 불편 하다. 매번 객체명뒤 점을 찍어 객체의 맴버를 보는 것은 그것을 아는 사람에게는 편집속도만 떨어뜨릴 뿐이다. 그러나 언어에 익숙치 않다거나, 남이 제공한 라이브러리를 사용할 경우는 이기능이 매우 유용하다. 특히 해당 맴버의 간단한 도움말까지 표시되면 API문서를 일일이 그때마다 검색하지 않아도 되어서 편리하다.

기존 자바 스크립트 편집기는 사실 이러한 기능이 부족한것이 사실 이었다. 그러나 지금 소개할 Aptana는 자바스크립트 전용 IDE를 표방한 몇 안되는 IDE중 하나이다. 이클립스 기반에 프러그인으로 개발되고 배포는 리치클라이언트와 플러그인 방식 모두를 지원한다. 따라서 기존 설치된 이클립스에서도 사용할 수 있고, 별도 설치를 통해 독립적인 IDE로 사용 할수도 있다. 다음은 Aptana의 실행 화면이다.

특히 Code Inspector가 매력 적이다. 노란 색으로 나오는 도움말도 매우 유용하다.

Apatana의 설치는 쉽다. 또한 무료로 사용 할 수 가 있다. (http://www.aptana.org/)

사용법은 기존 Eclipse와 동일하다. 단 디버거를 사용하려면 Firefox가 설치 되어 있어야 한다.

또한 기존 Ajax라이브러리들도 지원하는데, jQuery도 지원한다. 위 화면에서 객체의 도움말이 나올 수 있는것은 이 때문이다. 프로젝트 생성 시 jQuery프로젝트를 선택하여 생성 하면 된다.

 

jQuery 사용

위에서 소개한 Aptana를 설치 하였다면, 별도 jQuery설치는 필요 없다. 하지만 설치가 어려운것은 아니다. jQuery라이브러리는 55kb짜리 파일 하나로 되어 있다. 이를 HTML에 사용 선언을 하여 주면 된다.

 

<html>
  <head>
     <script type="text/javascript" src="path/jquery.js"></script>
     <script type="text/javascript">
       // Your code goes here
     </script>
   </head>
  <body>
    <a href="http://jquery.com/">jQuery</a>
   </body>
</html>

 

기존 자바 스크립트 라이브러리 사용과 차이가 없다. 단, 압축버젼과 그렇지 않은 버젼 두개의 파일을 제공하는데, 프로그래밍을 할 때는 디버깅을 위해 압축하지 않은 버젼의 파일을 사용하고, 배포할 경우 압축된 버젼을 사용하는 것이 좋다.

 

jQuery 의 시작 이벤트

보통의 자바스크립트 프로그래머들은 브라우져의 document가 모두 다운로드 되어진 상태에서 코드를 시작하기위해 다음과 같은 이벤트에 스크립트 코드를 넣는다.

  window.onload = function(){ ... }

그러나 이 경우 이미지 까지 다운로드가 모두 완료 된 후 이벤트가 호출되기 때문에, 큰이미지의 경우 실행속도가 늦은 것처럼 사용자에게 보일 수 있다. 따라서 jQuery는 이러한 문제를 해결하기위해 다음과 같은 이벤트를 제공한다.

 

$(document).ready(function(){
   // 이곳에 코드를 넣으면 된다.
});

 

 이 이벤트는 브라우져의 document(DOM)객체가 준비가 되면 호출이 된다. 따라서 이미지 다운로드에 의한 지연이 없다.

위 코드는 다음과 같이 생략하여 사용 가능하다.

 

$(function() { // run this when the HTML is done downloading }); 

 

사용자 이벤트 처리 - 클릭이벤트의 예

특정 태그를 클릭 했을경우 이벤트의 처리를 jQuery에서 어떻게 처리 하는지를 살펴 보자. 다음은 위 HTML예제의 앵커(a)태그 클릭 시 이벤트를 처리하는 코드 이다.

 

$("a").click(function(){
   alert("Thanks for visiting!");
});

 

 

jQuery에서 이벤트 처리는 콜백함수를 통해 수행된다. 이코드는 HTML에 있는 모든 앵커 태그의 클릭 시 팦업창을 통해 메시지를 출력해 준다.

코드를 보면 $()로된 문법을 볼 수 있을 것이다. 이것은 jQuery의 셀렉터 이다. $("a")가 의미하는 것은 HTML(브라우져의 DOM)에서 앵커태그 모두를 의미한다. 이후 .click()메소드는 이벤트 메소드로서 이곳에 콜백함수를 파라메타로 넣어 이벤트 처리를 수행 하는것이다. 함수는 위에서 처럼 익명(function(){...})이나 선언된 함수 모두를 사용할 수 있다.

 

jQuery의 셀렉터

$()로 시작하는 셀렉터를 좀더 살펴보자. jQuery는 HTML, DOM객체등을 CSS나 XPATH의 쿼리방법과 동일한 방법으로 선택 한다. 앞선 예처럼 문자열로 특정 태그를 선택하는 것은 CSS를 작성해 본 프로그래머라면 익숙할 것이다. 이와 같은 방법 외에도 다음과 같이 태그의 id를 통해 선택 할 수 있다.

 

$(document).ready(function() {
   $("#orderedlist").addClass("red");
});

 

 

위 코드는 id가 orderedlist인 태그에 red라는 CSS 클래스를 할당하는 코드 이다. 만약 이태그가 하위 태그를 가지고 있다면 다음과 같이 선택 할 수 있다.

 

$(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
});

 

이코드는 id가 orderedlist인 태그의 하위 태그 중 <li> 태그 모두에 blue라는 CSS 클래스를 할당하는 코드 이다. 이코드는 jQuery메소드를 이용 다음과 같이 바꾸어 사용 할 수도 있다.

 

$(document).ready(function() {
   $("#orderedlist").find("li").each(function(i) {
      $(this).addClass("blue");
   });
});

 

한가지 다른 점은 모든 태그에 동일하게 CSS 클래스를 적용하는 방식이 아닌 개별 태그를 선택하여 적용할 수 있다는 것이다.

XPath를 사용하는 예를 다음과 같은 것을 들 수 있다

 

//절대 경로를 사용하는 경우

$("/html/body//p")
$("/*/body//p")
$("//p/../div")

//상대경로를 사용하는 경우

$("a",this)
$("p/a",this)

 

다음과 같이 두 방식을 혼용하여 사용 할 수도 있다.

 

//HTML내 모든 <p>태그중 클래스속성이 foo인 것 중 내부에 <a> 태그를 가지고 있는것

$("p.foo[a]");

//모든 <li>태그 중 Register라는 택스트가 들어있는 <a> 태그

$("li[a:contains('Register')]");

//모든 <input>태그 중 name속성이 bar인 것의 값

$("input[@name=bar]").val();

 

이외에도 jQuery는 CSS 3.0 표준을 따르고 있어 기존 보다 더많은 쿼리 방법을 지원하고 있다. 자세한것은 jQuery의 API 설명을 참고 하라(http://docs.jquery.com/Selectors)

 

Chainability

jQuery는 코드의 양을 줄이기 위해 특별한 기능을 제공한다. 다음 코드를 보자

 

$("a").addClass("test").show().html("foo");

 

<a>태그에 test라는 CSS 클래스를 할당한다. 그후 태그를 보이면서 그안에 foo라는 텍스트를 넣는다. 이런 문법이 가능한 이유는 $(), addClass(), show()함수 모두가 <a>태그에 해당하는 객체를 결과로 리턴해주면 된다. 이를 Chainability라 한다. 좀더 복잡한 경우를 보자

 

$("a")
.filter(".clickme")
   .click(function(){
      alert("You are now leaving the site.");
   })
.end()
.filter(".hideme")
   .click(function(){
      $(this).hide();
      return false;
})
.end();

// 대상 HTML이다

<a href="http://google.com/" class="clickme">I give a message when you leave</a>
<a href="http://yahoo.com/" class="hideme">Click me to hide!</a>
<a href="http://microsoft.com/">I'm a normal link</a>

 

중간에 end()함수는 filter()함수로 선택된 객체를 체인에서 끝는 역할을 한다. 위에서는 clickme클래스의 <a>태그 객체를 끊고 hideme를 선택하는 예이다. 또한 this는 선택된 태그 객체를 말한다.

이런 Chainability를 지원 하는 jQuery메소드들에는 다음과 같은 것들이 있다.

 

  • add()
  • children()
  • eq()
  • filter()
  • gt()
  • lt()
  • next()
  • not()
  • parent()
  • parents()
  • sibling()

 

Callbacks

위에서 click()이벤트를 콜백함수를 통해처리하는 코드를 살펴 보았다. 콜백함수는 기존 자바나 .NET의 그것과 같다. 다음 코드를 보자

 

$.get('myhtmlpage.html', myCallBack);

 

먼저 $.get()은 서버로 부터 HTML(또는 HTML 조각)을 가져오는 함수 이다. 여기서 myCallBack함수는 전송이 완료 되면 호출되는 콜백 함수 이다. 물론 앞선 예의

click()이벤트 콜백처럼 익명함수 function(){}을 사용 해도 된다. 그러나 이와 같이 미리 선언된 함수를 콜백으로 사용할 경우 파라메타의 전달 방법은 좀 다르다. 흔히 다음과 같이 하면 될것이라 생각할 것이다.

 

$.get('myhtmlpage.html', myCallBack(param1, param2));

 

그러나 위와 같은것은 자바스크립트의 클로져(closure)사용에 위배가 된다. 클로져는 변수화 될수 있는 코드 블록을 이야기한다. 즉 스트링변수와 같이 파라메타로 전달될 수 있지만, 실행가능한 함수 인 것이다. 일반적으로 함수를 ()제외하고 이름만을 사용하면 클로져가 된다. 위의경우 $get()함수의 파라메타로 전달된 myCallBack함수는 클로져로 전달된것이 아닌 myCallBack()를 실행한 결과 값이 전달 된다. 따라서 다음과 같이 코드를 작성하여야 한다.

 

$.get('myhtmlpage.html', function(){
   myCallBack(param1, param2);
});

 

만약 선언된 함수가 아닌 익명함수를 콜백으로 사용할경우는 다음과 같이 하면 된다.

$.get('myhtmlpage.html', function(param1, param2){
//이곳에 코드를 넣는다.
});

 

jQuery 의 애니메이션

HTML의 태그를 사라지고 나타내게 하거나, 늘리고 줄이고, 이동시키는 애니매이션 동작은 많이 사용하는 기는 중 하나이다. jQuery는 다양안 애니메이션 기능을 메소드를 통해 제공한다. 다음 코드를 보자

 

$(document).ready(function(){
   $("a").toggle(function(){
      $(".stuff").hide('slow');
   },function(){
      $(".stuff").show('fast');
   });
});

이코드는 <a>태그중 stuff클래스가 할당된것을 토글로 느리게 감추고, 빨리 보이게 하는 함수 이다.

다음은 animate()메소드를 이용하여 여러 애니메이션을 합쳐 실행하는 예이다.

 

$(document).ready(function(){
   $("a").toggle(function(){
      $(".stuff").animate({ height: 'hide', opacity: 'hide' }, 'slow');
   },function(){
      $(".stuff").animate({ height: 'show', opacity: 'show' }, 'slow');
   });
});

 

위 코드는 높이와 투명도를 동시에 천천히 사라지고, 나타나게 하는 코드 이다.

 

jQuery에서의 Ajax

Ajax는 서버와의 비동기 통신을 말한다. 일반적으로 Ajax하면 요즘은 자바스크립트를 이용한 브라우져의 동적 DOM의 처리, 즉 DHTML, CSS등을 포함하지만, jQuery에서는 Ajax라는 네임스페이스를 통해 비동기 서버 통신을 하는것을 말한다.먼저 다음 예를 보자

 

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

 

이 예는 GET방식으로 서버에서 자바스크립트를 로딩하고 실행하는 코드 이다.

다음 예를 보자

 

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

 

이는 서버로 부터 POST방식으로 파라메터를 주어 데이터를 가져온 후 이를 success콜백을 이용해 처리하는 코드이다. 아마 Ajax에서 가장 많이 사용하는 코드일 것이다. success말고도 $.ajax()함수는 다양한 옵션을 제공한다. 자세한 내용은 API설명을 참조하라 (http://docs.jquery.com/Ajax)

다음 예는 이 옵션 중 async(비동기)방식을 사용할지 아닐지를 사용한 코드이다.

 

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

 

맺으며...

지금까지 jQuery에 대해 간단히 살펴 보았다. 혹자는 Dojo나 Extjs와 같이 버튼, 그리드등의 위젯이 지원되지 않는다고 실망할 것이다.그러나 jQuery는 Plugin을 지원한다. 이중 Interface와 같은 플러그인은 그 완성도가 매우 높다. 이것 말고도 수백개의 플러그인들이 홈페이지를 통해 공개 되어 있다.(http://docs.jquery.com/Plugins)

하지만 내 경험상으로 그리드와 같은 복잡한 위젯이 아니더라도 자바스크립크를 이용한 동적인 홈페이지와 Ajax를 통한 비통기 통신만으로도 대부분의 고객 요구와 문제를 해결 할 수 있다. 실제로 jQuery는 MSNBC와 같은 유명한 많은 사이트에서 사용되고 있다.(http://docs.jquery.com/Sites_Using_jQuery)

따라서 어떤 서비스를 제공하느냐에 따라 필요한 위젯을 플러그인을 사용하거나 직접 개발하여 사용하는것이 더 나은 전략이라 생각한다. 사실 미리 만들어진 위젯도 나에게 맞추어 사용하기 위해서는 그래픽, CSS등 많은 부분을 손 대야 한다. 차라리 기본 원리를 알고 이를 확장하는 것이 좀더 전문적이고 어려운 문제를 해결 할 수 있는 길이라 생각 한다.

시간이 허락 한다면 꾸준히 jQuery의 개발 경험을 공유 하고 싶은 마음 이다.


posted by 나는너의힘
:
JS/jQuery 2009. 5. 15. 00:09

jQuery/Core란?

 jQuery/Core란 jQuery의 핵심이 되는 것을 의미한다. 그만큼 우리가 jQuery를 사용할 때 많이 사용되는 부분이기도 하다.

하지만 Core라고해서 어려울것은 없고, 의외로 간단하다. Core를 표현하면 "$()"이렇게 된다.

 

참고로,

jQuery를 표현할 때 두가지가 있는데 한가지는 "jQuery(document).ready()" 이렇게 "jQuery"를 사용하는 방법과 "$(document).ready()" 처럼 "$"로 사용하는 방법이 있다. 이것은 사용자 취향에 맞게 선택해서 사용하면 된다.

 

정확한 개념을 알고 싶으신 분은 http://docs.jquery.com/Core 여기로 가시면 자세히 알 수가 있다. 하지만 저 처럼 영어에

약하신 분들은 이렇게 이해를 하시면 된다.

그럼 이제 사용법에 대해서 한번 살펴 봅시다.

 

jQuery 사용법

 여기서 사용되는 예제나 API는  http://docs.jquery.com/ jQuery공식 사이트에서 발췌한 것임을 미리 말씀드리고 시작합니다.

 

1. jQuery( expression, context )

  : expression는 String로 표현되고 특정 태그를 찾을때 사용되며, context는 Element나 jQuery으로 인자 값으로 받는다.

    즉, $("input:radio", document.forms[0]); 이와 같이 사용된다.

 

 2. jQuery( html )

  : jQuery는 인자값으로 html 태그를 받아 그 태그를 HTML페이지에 추가를 할 수가 있다.

    즉, 이렇게 $("<div><p>Hello</p></div>").appendTo("body") 사용이 되기도 하고,  $("<input/>").attr("type", "checkbox");

    이렇게도 사용되기도 한다.

    풀이 하자면 첫 번째는 "body"안에 "<div><p>Hello</p></div>"를 삽입(appendTo()는 특정 태그에 사입할 때 사용 )한다는

    애기고 두번째는 "input"를 생성하되 "type=checkbox"로 하여 태그를 생성하게 된다. 두번째는 HTML 마지막 부분에 삽입이

    된다.

 

 3. jQuery( elements )

  : DOM element(s) 를 인자로 받아 그 지역의 elements를 설정할 수가 있다.(한개 혹은 다수를 지정할 수가 있다.)

    $(document.body).css( "background", "black" ); -> HTML 배경색을 검정색으로 바꾼다.

    $(myForm.elements).hide() -> myForm의 이름을 가진 form안의 elements을 숨긴다.

 

 4. jQuery( callback )

  : 이것은 인자값을 함수로 지정을 할 수가 있다는 애기로 jQuery를 처음 시작하는 부분에서 많이 접해 봤을 것이다.

    즉, "$(document).ready(function(){....};)" 이 부분

    이렇게 사용하는 것은 특정 이벤트가 발생할 때 그 부분을 함수로 처리 하기 위해서 이다. 예를 들어 마우스를 클릭시

    경고창을 띄워주고 싶다면 아래와 같이 하면 된다. 

                           "$(document).click(function(){

                                   alert("마우스가 눌려짐!!");

                             };)"


- jQuery Object Accessors

 이번에는 직접 오브젝트를 엑세스할 수 있는 jQuery에 대해서 알아 본다. 뭐, jQuery 홈페이지에 가면 다 나와 있는 것들이긴 하지만 그래도 본좌의 나름 해석판을 듣고 싶다면 계속 봐도 된다. 다만, 본좌도 영어가 짧기 때문에 직접 실행해 봐서 이해 하기도 한 부분도 있고 이리저리 찾아 다니면서 알아낸 것 들도 있다. 그래서 영어 잘하시는 분 들이 봤을 경우 영 아니다 싶으면 자세히 답변을 남겨 주시면 참고하여 수정토록 하겠음...

그럼 오브젝트를 엑세스 할 수 있는 jQuery 에 대해서 알아 봅시다.

 

1. each( callback )

 : 해당 오브젝트에서 어떤 함수처리를 하고 싶을 경우 사용된다.  코드를 직접 보면 이해가 쉽게 된다.

    $(document.body).click(function() {
      $("div").each(function (i) {

        // 클릭 이벤트가 발생 되었을 경우 "div"태그에서만 글 색상을 변경하도록 한다.
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });

   이 코드를 실행 시키면 클릭 할때마다 색깔이 변경이 된다. 참고로 이 코드는 "body"안의 모든"div"태그를 뜻한다. 특정 "div"

   에서만 이벤트가 발생되기를 원하시면 그 태그의 인덱스를 찾아야 할 것이다.

 

2. size()

 : 해당 오브젝트의 Elements의 수를 알고자 할 때 사용된다.

    $(document.body).click(function () {
        $(document.body).append($("<div>"));
        var n = $("div").size();
        $("span").text("There are " + n + " divs." +
                     "Click to add more.");
    }).click(); // trigger the click to start

 

 3. length()

  : 해당 오브젝트의 Elements의 수를 알고자 할 때 사용된다. size()와 동일하다.

     $(document.body).click(function () {
      $(document.body).append($("<div>"));
      var n = $("div").length;
      $("span").text("There are " + n + " divs." +
                     "Click to add more.");
    }).trigger('click'); // trigger the click to start

 

 4. eq( position )

  : 해당 포지션에 위차한 태그를 찾는다. 한마디로 아파트로 비교하자면 몇호실을 찾는지와 같다. "405호실를 청소해라!"라는

    명령이 있다면 그 아파트의 "405호실"을 찾아가서 거기만 청소를 하면 된다. 구지 다른곳도 청소할 필요가 없다는 것이다.

    position의 위치는 0 부터 시작해서 -1까지다.

   

    $("p").eq(1).css("color", "red"); // "p"태그에서 1(0 부터 시작하므로 두번째를 의미한다.)번지에 해당하는 "p"를 변경한다.
 

 5. get()

  : 해당 태그의 Elements 들을 Array형태로 리턴한다. 즉, '$("div").get() 하면 모든 div태그 들을 Array 형태로 리턴한다.'

    한마디로 하면 DOM의 Elements를 배열로 리턴하는 것이다.

       function disp(divs) {
          var a = [];
          for (var i = 0; i < divs.length; i++) {
               a.push(divs[i].innerHTML);
          }
          $("span").text(a.join(" "));
        }
   
        disp( $("div").get().reverse() ); // div태그의 값들을 읽어 와서 그 값의 순서를 뒤집는다.

        // 예를 들어

        // <div>1</div><div>2</div><div>3</div> 이 있으면 reverse() 하면 3, 2, 1로 순서가 뒤집히게 된다.

 

 6. get( index )

   : index에 해당되는 위치의 element을 가져온다. 즉, 단일 element를 가져 오게 되는 것이다.

         $("*", document.body).click(function (e) { // body안의 모든 Elements에서 클릭 이벤트가 발생되면.
               e.stopPropagation();
               var domEl = $(this).get(0); // 클릭된 태그의 Elements중 0번지에 해당하는 Element를 가져온다.
               $("span:first").text("Clicked on - " + domEl.tagName); // 0번지의 태그이름을 출력한다.
          });

      이해하는데에는 어렵지 않을 것이다. 프로그래밍을 하다보면 위와 비슷한 함수를 많이 접해 보기 때문이다.

 

 7. index( subject )

  : subject의 인덱스 번호를 찾는다. 인덱스 번호도 0부터 시작된다.

      $("div").click(function () {
           // this is the dom element clicked
          var index = $("div").index(this); // "div"태그에서 클릭이벤트가 발생 될경우 그 "div"태그의 인덱스 찾아서 리턴한다.
          $("span").text("That was div index #" + index);
    });

 

jQuery/Core에 대해서는 여기서 마무를 하겠다. 이 외에도 Data Cash, Plugins에 대한 것도 있지만 아직은 다루지 않겠다.

시간이 짬짬이 날때 마다 글을 남기곤 있지만 회사 일도 바쁘다 보니 쉽게 글을 쓰지 못하는 것도 없지 않아 있다.

 

이 글을 쓰면서 예제 코드도 함께 올리려고 했는데 너무 도둑놈이 되는것 같아서 간단하게만 소개만 하였다. 뭐 본좌 나름대로

예제소스를 만들어 올리면 되지만...... 그렇게 하려면 시간이 많이 소모가 되고.... 잘못하다가는 회사에서 짤릴까봐 안했음..^^

 

다음은 Selector에 대해서 알아 볼 것이다. 나의 허접강의는 계속 된다..쭈욱~~~ ^^b


posted by 나는너의힘
:
JS/jQuery 2009. 5. 15. 00:08

jQuery 란?

 jQuery는 자바스크립트와 HTML 사이의 상호 작용을 강조하는 경량화된 웹 애플리케이션 프레임워크이다.

존 레시그에 의해, 2006년 뉴욕 시 바캠프(Barcamp NYC)에서 릴리즈되었다

 

jQuery는 MIT 라이선스와 GNU 일반 공중 사용 허가서의 듀얼 라이선스 하의 자유 오픈 소프트웨어이다.

 

기능

 jQuery는 다음과 같은 기능을 갖고 있다.

  • DOM 엘리먼트 선택
  • DOM 트래버설 및 수정 (CSS 1-3지원. 기본적인 XPath를 플러그인 형태로 지원)
  • 이벤트
  • CSS 조작
  • 특수효과 및 애니메이션
  • Ajax
  • 확장성
  • 유틸리티 - 브라우저 버전, "each"함수
  • 자바스크립트 플러그인

사용법

 jQuery는 한 개의 JavaScript파일로 존재한다. 공통의 DOM, 이벤트, 특수효과, Ajax함수를 포함한다. 다음 코드를 쓰면,

웸 페이지로 포함시킬 수 있다.

             

                                    <script type="text/javascript" src="path/to/jQuery.js"></script>

 

jQuery는 두 가지의 상호 작용 스타일을 갖고 있다.

  • $함수 이용 . jQuery 오브젝트의 팩토리 메소드이다. 이 함수들은 "chainable"하다: 각각은 jQeury 오브젝트를 리턴한다.
  • $. - 가 붙은  함수 이용. 이들 함수는 jQuery 오브젝트 그 자체와 연동되지는 않는다.

일반적으로 여러 개의 DOM노드들을 조작하는 웍플로우는 $함수로 시작된다. CSS 셀렉터 스트링을 가지고 호출된다. 결과적으로

0개 혹은 그 이상을 HTML 페이지 내의 엘리먼트를 리퍼런스하는 jQuery 오브젝트가 리턴된다. 이 노드 집합들은 jQuery 오브젝트에

대해 인스턴스 메소드 들을 적용함으로써 조작될 수 있다. 혹은 노드들 그 자체가 조작될 수 있다. 예를 들면 다음과 같다.

 

$("div.test").add("p.quote").addClass("blue").slideDown("slow");

.. div 태그가 달리 모든 엘리먼트를 찾되, 클래스 애티르뷰가 test인 것을 찾는다. <p>태그를 찾되, 클래스 애트리뷰트가

quote인 것을 찾는다. 찾아낸 각각의 엘리먼트에 대해 클래스 애트리뷰트 blue를 추가한다. 그 뒤 애니메이션 효과를 주어 아래쪽으로

슬라이드(미끄러지게) 시킨다. $및 add함수는 찾아낸(matched) 집합(set)에 영향을 준다. addClass및 slideDown는 리퍼런스된

노드들에 영향을 준다.

 

$.가 앞에 붙은 함수들은, 글로벌 프로퍼티나 비해이비어에 영향을 주는, 간편한(유틸리티)메소드들이다. 예를 드면 다음과 같다.

$.each([1,2,3], function() {
  document.write(this + 1);
});

... 234를 도류먼트에 출력한다.

 

Ajax 루틴들은 $.ajax및 관련 코드를 이용하여 수행할 수 있다. 이를 사용하여, 원격 데이터(remote data)를 로드하거나 조작할 수 있다.

$.ajax({
            type: "POST",

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

파라미터 name=John, location=Boston을 주면서 some.php에 요청을 보낸다. 요청이 성공적으로 수행되었으면, 그 응답이 alert()된다.

 

* 위 내용은 위키백과에 등록된 내용입니다.(http://ko.wikipedia.org/wiki/JQuery)

 

 

 

잠든거인의 jQuery ( 본좌 생각 )

 jQuery가 무엇일까? 라는 고민을 가지고 jQuery를 처음 접하게 되었다.

jQuery를 알게 된 것은 아는 형이 회사에서 jQuery를 쓰고 있다는 애기를 듣고 난 후였다. 처음에는 Query라고 해서 SQL Query문을

만들어 주는 것이 아닌가?라느 생각을 가졌었다.(참 민망하다..)  ㅡ.ㅡ;;

나중에야 검색을 하고 난후에야 웹 페이지에서 쓰이는 Javascript 프레임워크라는 걸 알게 된것이다.

 

프레임워크라고 하면 배우기만 하면 쓰기 편안한데, 막상 배우려면 시간이 꽤 많이 든다. 프로그래머라면 이 말에 공감이 갈 것이다.

어떤 프로그래머들은 프레임워크에 대해 안좋은 생각을 가지고 있는 분들고 있을 것이다. (뭐, 생각은 자유니깐..^^v)

 

본좌 또한 배우기에 귀찮다는 생각을 가지고 있었기에 열나게 DOMScript 만을 썼었다. 그러나 막상 개발에 들어가니 Javascript코드가

굉장히 길어지게 된것이다. 뭐 나만 보는 것이면 상관이 없었지만 다른 사람이 만약 내가 개발한 코드를 보고 분석할려면 시간이 좀

걸릴 것이다.

또한, 코드가 길다보니 마우스의 휠과 Ctrl + F 만을 열나게 사용해야만 했다. 본좌는 이게 가장 싫었다.

분할해서 Javascript 코드를 작성하면 되지 않냐! 라는 말 하시는 분들도 계시겠지만 본좌는 단순한 걸 좋아 한답니다. ^^v 

 

그래서 코드를 경량화 시켜보고자 우선 Prototype을 배우고자 했지만, 갑자기 jQuery가 생각 났고, 누군가 Prototype보다 가볍다고

해서 jQuery를 쓰게 된 것이다.

 

우선 jQuery를 어떻게 사용하는 지를 알아 보자.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "
http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<script src="
http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(document).ready(function(){  
             $("#my").css("border", "3px solid red")
     });
</script>
</head>
<style>
div {
          float: left;
          width: 90px;
          height: 90px;
          padding: 5px;
          margin: 5px;
          background-color: #EEEEEE;
     }

</style>
<body>
   <div id='you'></div>
   <div id='my'></div>

</body>
</html>

 

-------------- 실행 경과 -----------------

jQuery의 시작은

$(document).ready(function(){

       // 여기에 코딩!!

});

이렇게 시작이 된다. 이제 가운데 부분에 코딩만 하면 되는 것이다.

 

$(document).ready(function(){..}) 이부분에 자세히 알아 보면

$(document).ready(function(){..})  == window.onload =  function(){....} 이런 공식이 된다.

 

하지만 약간 다르다. 그 이유를 살펴보면

대부분 자바스크립트 프로그래머들은 브라우저의 document가 모두 로딩되고 난 후에 코딩을 하기 위해서 <body> 태그에

onload 이벤트를 사용하거나

window.onload =  function(){....} 이와 같은 스크립트 코드를 넣는다.

그러나 이 경우에는 이미지까지 다운로드가 모두 완료 된 후 이벤트가 호출되기 때문에, 큰 이미지의 경우 실행속도가

늦은 것처럼 사용자에게 보일 수 있다. jQuery는 이러한 문제를 해결하기 위해 다음과 같은 이벤트를 제공한다.

 

$(document).ready(function(){

                // 코딩........

}) 

 

이 이벤트는 브라우저의 document(DOM)객체가 준비가 되면 호출이 된다. 따라서 이미지 다운로드에 의한 지연이 없다.

위 코드를 생략하면

 

$(function(){

             // 여기에다가 코딩을 하세요

});

 

이렇게 사용이 가능합니다.

 

이것으로 jQuery란 무엇인지 대한 강좌는 마치겠습니다. 


posted by 나는너의힘
:
JS 2009. 5. 14. 22:50

입력상자 한글/영문 설정하기 [style="ime-mode:active"]
 

style="ime-mode:auto"(자동변경)->한/영 전환가능

style="ime-mode:active"(한글모드) ->한/영전환가능

style="ime-mode:inactive"(영문모드)->오직영문

style="ime-mode:disabled"(영문모드)->한/영전환가능

style="ime-mode:deactivated"(한글모드)->한/영전환가능

http://jjong0420.tistory.com/entry/%EC%9E%85%EB%A0%A5%EC%83%81%EC%9E%90-%ED%95%9C%EA%B8%80%EC%98%81%EB%AC%B8-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0
posted by 나는너의힘
:
JS 2008. 8. 18. 02:47

<html>
<head>
<script language="javascript">

function textCounter(theField,maxChars)
{
var strCharCounter = 0;
var intLength = theField.value.length;

if((event.keyCode == '37') || (event.keyCode == '39') || (event.keyCode == '8'))
{
return ;
}
for (var i = 0; i < intLength; i++)
{
var charCode = theField.value.charCodeAt(i);
//한글일 경우
if (charCode > 128)
{
strCharCounter += 2;
}
else
{
strCharCounter++;
}

if(strCharCounter >= (maxChars)+1)
{
eval("alert('한글" + maxChars/2 + ", 영문" + maxChars+ "자 제한입니다. 초과된 문자는 잘립니다.')");
//theField.value = "";
theField.value = theField.value.substring(0,intLength-1)
return;
}
}
}


function textCounter2()
{
//document.a.tel.value = document.a.tel.value.substring(0,5);
var maxChars =10;
var strCharCounter = 0;
var intLength = document.a.tel.value.length;

for (var i = 0; i < intLength; i++)
{
var charCode = document.a.tel.value.charCodeAt(i);
//한글일 경우
if (charCode > 128)
{
strCharCounter += 2;
}
else
{
strCharCounter++;
}

if(strCharCounter >= (maxChars)+1)
{
eval("alert('한글" + maxChars/2 + ", 영문" + maxChars+ "자 제한입니다.맞게 입력하세요.')");
return;
}
}
}

</script>
</head>
<form name="a">
<body>
전번 입력: <input type="text" size =20 name="tel" onkeyup="textCounter(this,10);">
<br>
저장 : <input type="button" value="save" onClick="textCounter2();">

</form>
</body>
</html>

출처 : Tong - 삽질만이 살 길이다님의 Javascript통

posted by 나는너의힘
: