jquery 정리

jQuery 2011. 12. 26. 09:31

 $.ajax({           // 실행 함수
  type:"POST",      // get.post 가능
  url:"ajax.jsp",       // 호출 url
  dataType: "json",              //date 타입  xml,text 등
  data:"point=1&gift=2",   // url 에 보낼 파라미터 값
  timeout:3000,              //제한시간 설정 가능
  cache:false,                // true, false
  error:function(request, status, error){   // 에러 발생 시   status 400 이 성공 그 외 404, 500 등
   alert("에러!");
  },
  success:function(msg){     // 성공 시 콜백  msg 에 data
   alert("성공");
  },
  beforeSend:function(){     // ajax 통신을 시작하기 전에 콜백
   alert("통신시작");
  },
  complete:function(){        //완료 후 실행할 콜백 함수 정의
   alert("통신완료");
  }
 });

 /**
  *  상황에 따라 적절하게 함수 사용 아래 상황 예제 샘플
  *  html document  완성 시  onload 와 유사함
  */
  jQuery(document).ready(function(){
   $.ajax({
    type:"GET",
    url:"ajax.jsp",
    data:param,
    success:function(msg){
     html_id.innerHTML = msg;    // text 로 태그 통신 시 html 삽입 하기
     $('.html_id').append(msg);    // 위와 같은 jQuery 방식 이거 쓰지마셈
     // '.html_id' <-- 이놈은 <div class='html_id'></div>
     // '#html_id' <-- 이놈은 <div id='html_id'></div>
     // 선언을 어떻게 하냐에 틀리고 적절하게 사용 하면 됨
    }
   });
  });

  /**
   * 엘리먼트 클릭 등 dom 의 변화에 따른 이벤트  id , class 등 지정 가능
   *  Ex id = # , class 는 . 으로 구분 css 문법과 같음~!
   */
 $(function() {
  $('#divId').click(function() {  // function 으로 감싸지 않고 아래의 예제처럼도 사용가능
   $.ajax({
    type:"GET",
    url:"ajax.jsp",
    data:"page="+3,
    success:function(msg){
     html_id.innerHTML = msg;    // text 로 태그 통신 시 html 삽입 하기
     $('.html_id').append(msg);    // 위와 같은 jQuery 방식
    }
   });
  });
 }); 
 
 /**
 * form submit 시 콜백 id, class 등 지정
 */
 $("formName").submit(function(){
  
 });
 
  /**
  * 함수 호출을 통한 ajax
  * <a href='board_list.php?page=1&code=2' >page전환</a> <--이거를
  * <a href='paging(1,2)' >page전환</a> 이런식으로 함수에 보내서 하면 되겠지~?
  */
 function paging(page,code){
  // POST 방식도 아래 param 처럼 만들어서 보내면 됨
  var param = "board_code="+code+"&page="+page;
  $.ajax({
   type:"GET",
   url:"board_list.php",
   dataType: "text",  
   data:param,
   success:function(msg){
    board_list_area.innerHTML = msg;
   }
  });
 }

 $(function() {
  $('[name=samju]').click(function() { 
   alert($(this).val());
  });
 }); 

 $(function() {
  $('[name=samju]').click(function() { 
   $(this).val(function(index,value){
    alert(this.value);
    alert(this.index);
   });
  });
 }); 

  $("button").click(function () {
      var text = $(this).text();
      $("input").val(text);
    });


  $("input").keyup(function () {
      var value = $(this).val();
      $("p").text(value);
    }).keyup();

 $('select.foo option:selected').val();    // 드롭박스에서 선택된 것을 가져옴
 $('select.foo').val();                    // 드롭박스에서 좀더 쉽게 값을 가져옴
 $('input:checkbox:checked').val();        // 체크가 된 체크박스의 값을 가져옴
 $('input:radio[name=bar]:checked').val(); // 라디오버튼 중 선택된 값을 가져옴

/**

<p>
  Once there was a <em title="huge, gigantic">large</em> dinosaur...
</p>

  The title of the emphasis is:<div></div>
  em 태그에서 title 속성을 가져와 title 변수로 넣음
**/

var title = $("em").attr("title");
  $("div").text(title);

  $('#greatphoto').attr({
   alt: 'Beijing Brush Seller',
   title: 'photo by Kelly Clark',
   src : './img/image.jpg'
});
// ID 가 greatphoto 인 이미지 태그에서 attr 속성을 불러오며 바로 값도 넣을 수 있음

$("button:gt(1)").attr("disabled","disabled"); // 버튼등의 비활성도 가능

/**
 <div></div>
  <div></div>
  <div></div>
 **/


    $("div").html("<b>Wow!</b> Such excitement...");
    $("div b").append(document.createTextNode("!!!")) .css("color", "red");

// Wow!!!! Such excitement...   Wow   와  Such excitement 사이에 !!! 빨간색 텍스트를 추가

 

//----------------------------------------------------------
// 배열 관련

var x = [0, 3, 1, 2];
console.log(x.reverse()); // x = [2, 1, 3, 0]
console.log(x.join(" – ")); // x = "2 - 1 - 3 - 0"
console.log(x.pop()); // x = [2, 1, 3]
console.log(x.unshift(-1)); // x = [-1, 2, 1, 3]
console.log(x.shift()); // x = [2, 1, 3]
console.log(x.sort()); // x = [1, 2, 3]
console.log(x.splice(1, 2)); // x = [2, 3]


// <div>Click here</div> 클릭 하면 파란색으로 바꾸기 파란색 -> 검정색 이런식..
$(document.body).click(function () {
      $("div").each(function (i) {
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });


/**
  <div></div>
  <div></div>
  <div id="stop">Stop here</div>
  <div></div>
 
3번 째 div 를 만나면 stop   false 를 리턴하면 멈춤
**/

 $("button").click(function () {
      $("div").each(function (index, domEle) {
        // domEle == this
        $(domEle).css("backgroundColor", "yellow");
        if ($(this).is("#stop")) {
          $("span").text("Stopped at div index #" + index);
          return false;
        }
      });
    });

 

/**

reverse() : 배열 순서를 뒤집기
 join('key') : key 값으로 배열요소를 문자열로 만들어줌
pop() : 배열의 맨 마지막 요소를 삭제하고 삭제된 해당 값을 반환함
unshift(값) : 값을 배열의 0번째 요소에 삽입하고 이전 요소를 하나씩 뒤로 밀어낸 후, 배열의 길이를 반환함(ie는 undefined를 반환함)
shift() : 배열의 맨 처음 요소를 삭제하고 삭제된 해당 값을 반환함
splice(index, 몇개) : index위치 부터 몇개를 삭제한 후 삭제된 요소들을 반환해 줍니다.


**/

// $.inArray(value, array);    값으로 배열 index 찾기
var index = $.inArray(2, [1, 2, 3, 4, 5]);          // 해당 index 변수에는 1이 할당된다.


$.makeArray(object);
//NodeList와 같은 변환될 유사 배열 객체, 이 함수를 사용하면 jQuery를 사용하지 않고 XML 문서를 순회할 때 NodeList 객체를 편리하게 다룰 수 있다


// 마우스 오버 이벤트 샘플
$("li.fade").hover(function(){$(this).fadeOut(100);$(this).fadeIn(500);});

$("li").hover(
  function () {
    $(this).append($("<span> ***</span>"));    //.appendTo("<span> ***</span>"") 마지막 요소에 추가
  },
  function () {
    $(this).find("span:last").remove();
  }
);


// Text 붙이기
// div class="inner">Hello</div>

$('<p>Test</p>').insertAfter('.inner');  //class inner 뒤에 <p> Tag 를 붙임  반대  .insertAfter()  앞에 붙이기  $('.inner').after('<p>Test</p>');

// Tag 를 DIV 로 감싸기

// <div class="inner">Hello</div>
//   <div class="new">
// <div class="inner">Hello</div>
//</div>

$('.inner').wrap('<div class="new" />');  // 위와 같이 태그를 감쌀 수 있음   // .wrapAll( wrappingElement )  로 많이 사용?

 

'jQuery' 카테고리의 다른 글

jquery 동적 js 실행  (0) 2012.01.10
jQuery json load  (0) 2012.01.10
아주쉬운 jQuery & jQuery Ajax  (0) 2011.10.11
jQuery 커버플로우  (0) 2011.07.29
jQuery 유용한 함수(?) eq  (0) 2011.06.23
블로그 이미지

스마트전

,