본문 바로가기
JQuery/JQuery

JQUERY 간단 정리

by 놀러와요 2020. 4. 22.
반응형

jquery_tut1.html - 기본 셀렉터

 

$("*") : 모두

$("div p") : 모든 <div>에 포함된 모든 <p>

$("#loginID") : id="loginID"

$(".Columns") : class="Columns"

$("p > a") : <p>에 포함된 한 단계 아래 레벨의 모든 <a>

$("div + p") : <div> 와 같은 레벨인 다음 <p>

$("div ~ p") : <div> 와 같은 레벨인 모든 <p>

 

// 개체 숨김

$(selector).hide();

 

 

jquery_tut2.html - 필터

 

$("a[title]") : title 속성이 있는 <a>

$("a[href^=mailto:]") : href 속성이 mailto로 시작하는 모든 <a> (^는 문장의 처음을 나타내는 정규표현식)

$("a[href$=.pdf]") : href 속성이 pdf파일 링크인 모든 <a> ($는 문장의 끝을 나타내는 정규표현식)

$("a[href*=taeyo.net]") : href 속성에 taeyo.net이라는 값이 포함되어 있는 모든 <a>

$("input[type=text]") : type 속성이 "text"인 모든 <input>

 

$("tr:first"): 모든 <tr> 중 첫 번째 <tr>

$("tr:last"): 모든 <tr> 중 마지막 <tr>

$("tr:not('selector')"): 모든 <tr> 하위 개체 중 selector에 해당되지 않는 개체

$("tr:even"): 모든 <tr> 중 짝수 번째(0부터 시작)

$("tr:odd"): 모든 <tr> 중 홀수 번째(0부터 시작)

$("tr:eq(0)"): 모든 <tr> 중 1 번째

$("tr:gt(1)"): 모든 <tr> 중 2 번째 이후

$("tr:lt(2)"): 모든 <tr> 중 3 번째 이전

 

$(":header"): 모든 헤더 (<h1>, <h2>, <h3> 등)

$(":animated"): 애니메이션이 포함된 모든 개체

$(":contains('text')"): text를 포함하는 모든 개체

$(":empty"): 하위 개체를 가지지 않는 모든 개체 (내부 텍스트를 가지지 않는 개체도 해당)

$(":has('selector')"): selector에 해당하는 모든 개체

$(":parent"): 모든 상위 개체 (내부 택스트를 갖는 개체도 해당)

 

$("td:nth-child(1/even/odd)"): 모든 1(최소 값은 1) 번째 <td> / 짝수 번째 <td> / 홀수 번째 <td> (테이블에서 세로 줄)

$("td:nth-child(2n+1)"): 모든 첫 번째 <td>(+1) 부터 2의 배수 번째 <td> (테이블에서 매 두 번째 세로 줄)

$("td:first-child"): 모든 첫 번째 <td> (테이블에서 첫 번째 세로 줄, nth-child(1)로 대체)

$("td:last-child"): 모든 마지막 <td> (테이블에서 마지막 세로 줄)

$("td:only-child"): 모든 최하위 <td>

 

// 선택된 개체에 스타일 시트 적용

$(selector).css("background", "yellow");

 

// 상위 개체

$(selector).parent()

 

 

jquery_tut3.html - 폼 필터 및 조작 기능

 

$(":input"): 모든 <input>, <textarea>, <select>, <button>

$(":text"): type="text"인 모든 <input>

$(":password"): type="password"인 모든 <input>

$(":radio"): type="radio"인 모든 <input>

$(":checkbox"): type="checkbox"인 모든 <input>

$(":submit"): type="submit"인 모든 <input>

$(":image"): type="image"인 모든 <input>

$(":reset"): type="reset"인 모든 <input>

$(":button"): type="button"인 모든 <input>

$(":file"): type="file"인 모든 <input>

$(":hidden"): type="hidden"인 모든 <input>

 

$(":enabled"): enable 상태인 모든 개체

$(":disabled"): disable 상태인 모든 개체

$(":checked"): 체크된 모든 개체

$(":selected"): 선택된 모든 개체

 

// 페이지 로드시에 할 일

$(document).ready(function(){

});

 

// 클릭 이벤트, 마우스 오버 이벤트를 설정, color 스타일 값 red로 변경

$("#id").click(someFunction).mouseover(otherFunction).css("color", "red");

 

// 선택된 개체들에 대해 실행할 함수 지정

$(selector).each(function(i) {

// i: 선택된 개체들의 인덱스

// $(this): 선택된 개체

});

 

 

jquery_tut4.html - 조작 기능

 

// 개체의 태그(선택된 개체가 여러 개일 경우 첫 번째 것)

$(selector).html()

 

// 개체의 태그를 val로 대체

$(selector).html("val")

 

// 개체의 텍스트

$(selector).text()(선택된 모든 개체의 텍스트를 결합)

 

// 개체의 텍스트를 val로 대체

$(selector).text("val")

 

// 개체의 내부에 content를 끝에 추가

$(selector).append("content")

 

// 개체의 내부에 content를 앞에 추가

$(selector).prepend("content")

 

// id를 모든 <a> 내부의 끝에 추가

$("#id").appendTo("a")

 

// id를 모든 <a> 내부의 앞에 추가

$("#id").prependTo("a")

 

// 개체의 다음에 content 추가

$(selector).after("content")

 

// 개체의 이전에 content 추가

$(selector).before("content")

 

// id를 모든 <a> 다음에 추가

$("#id").insertAfter("a")

 

// id를 모든 <a> 이전에 추가

$("#id").insertBefore("a")

 

// 선택된 개체의 하위 개체들을 제거

$(selector).empty()

 

// 선택된 개체들을 제거

$(selector).remove()

 

// 선택된 개체들 복사 및 선택

$("#id").clone()

 

// 선택된 개체들 복사 및 선택(이벤트 처리 포함. onclick, mouseiver...)

$("#id").clone(true)

 

 

jquery_tut5.html - 탐색 기능

 

// 모든 <div> 중 1 번째

$("div").eq(0)

 

// 선택된 개체 집합을 이전 상태로 변경(end())

$("div:odd").eq(0).css("background", "orange")

.end()    // $("div:odd")와 동일

.eq(1).css("background", "blue"); // $("div:odd").eq(1).css("background", "blue");

 

// 선택된 개체를 메모리에서 :odd 재검색(filter())

$("div").filter(":odd").end() // $("div")와 동일

 

// 선택된 개체를 메모리에서 하위 노드의 <p> 재검색(find())

$("div").find("p")

 

// 선택된 개체를 메모리에서 :even 아닌 것을 재검색(not())

$("div").not(":even").end() // $("div")와 동일

 

// 개체 확인(is())

var $myDiv = $("div").eq(5); // 변수명 앞에 '$'는 jQuery 개체 참조형

if ( $myDiv.is("div") ) { // 개체 확인

$myDiv.css("border", "4px solid yellow");

}

$myDiv.is(".orange, .blue, .lightblue") // 세 클래스 이름 중 하나만 일치해도 true

 

// 선택된 개체들의 텍스트를 배열로 변환(map())

var arr = $("div").map(function()

{

return $(this).text().toUpperCase();

});

 

// 다음 개체

$(selector).next(expr)

 

// 다음 모든 개체

$(selector).nextAll(expr)

 

// 이전 개체

$(selector).prev(expr)

 

// 이전 모든 개체

$(selector).prevAll(expr)

 

// 선택된 개체에 추가

$(selector).add(expr)

 

// 상위 개체 선택

$(selector).parent(expr)

 

// 고유한 상위 개체들 선택

$(selector).parents(expr)

 

// 같은 레벨인 개체들 선택

siblings(expr)

 

 

jquery_tut6.html - css와 attr 기능

 

// 스타일 시트 적용

$(this).css({ 'color':'yellow','font-weight':'bolder' });

 

// 모든 <div>를 blue 클래스로 지정

$("div").addClass("blue")

 

// 선택된 <div> 중 blue 클래스가 존재하면 true

$("div").hasClass("blue")

 

// 선택된 <div>에서 blue 클래스 제거

$("div").removeClass("blue")

 

// 선택된 <div>에서 blue 클래스 적용 여부를 반전

$("div").toggleClass("blue")

 

// 첫 <img>의 src 값

$("img").attr("src")

 

// 모든 <img>에 스타일을 적용

$("img").attr({ css: { border: "1px", height : "100" } })

 

// 모든 <img>의 title에 hello 적용

$("img").attr("title", "hello")

 

// 모든 <img>의 title에 function()의 리턴 값 적용

$("img").attr("title", function())

 

// 모든 <img>에서 title 속성 제거

$("img").removeAttr("title")

 

 

jquery_tut7.html - 이벤트

 

// id="MyBtn"에 click 이벤트 추가

$("#MyBtn").bind("click", function(e)

{

// MyBtn 클릭시 수행

// 사용 가능한 이벤트: blur, focus, load, resize, scroll, unload, beforeunload,

  click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter,

  mouseleave, change, select, submit, keydown, keypress, keyup, error

});

$("#MyBtn").bind("click", { name: "Taeyo", gender: "남" }, function(e)

{

alert(e.data.name + " / " + e.data.gender); // 두 번째 매개변수 활용

});

 

// id="MyBtn"에 click 이벤트 제거

$("#MyBtn").unbind("click");

 

// id="MyBtn"에 일회성 click 이벤트 추가

$("#MyBtn").one("click", function(e) {

alert("누가 내 버튼을 클릭한 것이냐?");");

});

 

// id="MyBtn"에 click 이벤트 작동

$("#MyBtn").trigger("click");

 

 

기타

// 값 얻어오기

$("#id").val();

 

$('form#login'): id="login"인 <form>

$('label.optional'): class="optional"인 <label>

 

 

AJAX

// 기본

$.ajax({

url: 'scripts/login.php',

type: 'POST',

data: 'account='+$('#account').attr('value')+'&password='+$('#password').attr('value'),

error: function()

{

  alert('Error loading XML document');

},

success: function(xml)

{

  $(xml).find('item').each(function()

  {

   var item_text = $(this).text();

   $('<li></li>').html(item_text).appendTo('ol');

  });

}

});

 

// 페이지로 데이터 보내기

$.post('save.cgi',{ text: 'my string', number: 23 },

function()

{

  alert('Your data has been saved.');

}

);

 

 

버전 1.4 추가 사항

// 개체 생성

$("<div>",

{

id: "foo",

css: {

height: "50px",

width: "50px",

color: "blue",

backgroundColor: "#eeeeee"

},

click: function() {

$(this).css("backgroundColor", "red");

}

}).appendTo("body");

 

// eq(-n)과 get(-n)

$("div").eq(-2); // 뒤에서 두 번째 개체

$("div").get(-2); // 뒤에세 두 번째 개체의 값

 

// first(), last()

first(): eq(0)과 같다

last(): eq(-1)과 같다

 

// toArray()

var arr = $('li').toArray(); // 모든 <li>를 arr에 배열로 저장

 

// attr()에서 현재 값을 매개변수로 참조 가능

$("#photo").attr("alt", function(index, value)

{

return "사랑하는 " + value; // value는 현재 값

});

 

// 함수로 값을 할당할 수 있는 함수들

.css(), .attr(), .val(), .html(), .text(), .append(), .prepend(), .before(), .after(),

.replaceWith(), .wrap(), .wrapInner(), .offset(), .addClass(), .removeClass(), .toggleClass()

 

// 매개변수로 현재 값을 참조할 수 있는 함수들

.css(), .attr(), .val(), .html(), .text(), .append(), .prepend(), .offset(),

.addClass(), .removeClass(), .toggleClass()

 

// 지정된 css를 클래스를 모두 적용

$("input").toggleClass("normal selected");

 

// .data()에 키가 없으면 값을 반환하도록 개선

$('body').data('foo', 52); // boby에 foo=52

$('body').data('bar', { myType: 'test', count: 40 }); // boby에 bar={ myType: 'test', count: 40 }

alert($('body').data('foo')); // 52를 경고창에 출력

alert($('body').data()); // { foo: 52, bar: { myType: 'test', count: 40 } 경고창에 출력

 

// has 필터와 동일

.has(value)

.has(selector)

 

// .nextUntil(), .prevUntil(), .parentsUntil() 추가

$("#div1").nextUntil("div").css("background-color", "red"); // 다음 div까지 선택

 

// .add(), .closest() 함수가 컨텍스트를 가질 수 있도록 개선

Ajax에서 개체를 받아온 경우 동적으로 그 개체에게 add()를 사용하여 추가 가능

 

// .detach() 이벤트 핸들러를 남겨두고 개체를 제거

$(document).ready(function() {

var $p = $("p").click(function()

{

  $(this).css("background-color", "yellow");

});

$("p").detach(); // DOM에서 <p> 제거

$p.css("color", "red"); // 폰트 색깔 변경

$p.appendTo("body"); // 개체를 <body>에 붙임

}); // <p>를 클릭하면 배경이 노란색으로 바뀜

 

// 이벤트 다중 설정

$("#box").bind({

click: function()

{

  $(this).text("click");

},

mouseenter: function()

{

  $(this).text("mouseenter");

},

mouseleave: function()

{

  $(this).text("mouseleave");

}

});

 

// focusin, focusout 이벤트 추가(focus, blur와 동일하나 버블링을 지원. live() 사용 가능.)

 

// .delay() 함수 시행 지연

$('#foo').slideUp(1000).delay(500).fadeIn(1000);

 

// .clearQueue() 큐에 존재하지만 아직 실행되지 않은 모든 함수들을 제거

 

// 빈 개체인지 확인

jQuery.isEmptyObject({}) // true

jQuery.isEmptyObject({ foo: "bar" }) // false

 

// 개체가 {}로 구성되어 있는지 확인

jQuery.isPlainObject({}) // true

jQuery.isPlainObject(new MyClass()) // false

jQuery.isPlainObject(new Date()) // false

 

// 첫 번째 매개변수로 지정된 DOM 개체 안에 두 번째 매개변수인 DOM 개체가 포함되어 있는지 확인

jQuery.contains($("p")[0], document.body); // false

jQuery.contains(document.body, $("p")[0]); // true

 

 

//jQuery JSON 사용

 

// Create test user Object

var user = new Object();

user.name = "gildong";

user.age = 18;

 

// Object to JSON

var userJSON = $.toJSON(user);

alert("userJSON = " + userJSON); // { name : "gildong", age : 18 }

 

// JSON to Object

var userObj = $.evalJSON(userJSON);

alert("userObj.name = " + userObj.name); // gildong

alert("userObj.age = " + userObj.age); // 18

 

 

// 양쪽 공백제거

var str =" asdf ";

$.trim(str);

 

// div 블럭요소를 부드럽게 display함

$("#testDiv").fadeIn('slow');

 

// div 블럭요소를 display함

$("#testDiv").show();

 

// div 블럭요소를 none시킴

$("#testDiv").hide();

 

// radio버튼 중 선택된 요소의 값을 리턴

var san = $('input:radio[name:san]:checked').val();

 

// select박스에서 선택되어 있는 index의 text노드값을 리턴

$('#sido_cd_mini option:selected').text();

 

// select박스에서 선택되어 있는 index의 value값을 리턴

$('#sido_cd_mini option:selected').val();

// 자식창에서 부모창으로 값전송

부모창id 자식창ID의 속성값

$('#usserip',opener.document).val($('#ip').val());

 

// 요소의 display 속성을 none일 경우 block으로 blick일 경우 none으로변경

$("#testDiv").toggle();

 

// 쿠키

https://github.com/carhartl/jquery-cookie // jQuery 쿠키 js 다운로드 및 참조

 

js 파일(jquery.cookie.js) 임포트 한 후

 

<쿠키생성>

 

1. 세션 쿠키(Session Cookie)

 

세션 쿠키는 브라우저 열려있는 동안만 유지된다

 

$.cookie('key' , 'value');

 

2. 만료일 지정한 쿠키

 

$.cookie('key' , 'value', { expires : 값 });

 

값의 단위는 일(日)단위 이다

 

주의할 점은 위 생성방식 모두 디폴트로 쿠키가 만들어진 페이지 경로에만 쿠키가 적용된다

 

모든 페이지에 쿠키를 적용하려면 아래와 같이 path : '/' 를 설정 해야 한다

 

$.cookie('key' , 'value', { expires : 값, path : '/' });

 

$.cookie('key' , 'value', { path : '/' });

 

<쿠키 읽기>

 

$.cookie('key');

 

위처럼 하면 저장된 값을 반환한다. 해당 key가 없다면 null 반환

 

<쿠키삭제>

 

$.cookie('key', null);

 

path 옵션을 주어 쿠키를 만들었다면 삭제할때 역시 같은 path 옵션을 줌 (이것 떄문에 삽질 대박함)

 

<쿠키 생성시 옵션 항목>

 

expires : 365

 

쿠키 만료를 일단위로 설정한다 생략하면 세션 쿠키로 만들어진다

 

path : '/'

 

쿠키가 적용되는 페이지 경로. 사이트 전체 페이지에 적용하려면 위와같이 설정

domain : 'domain.com'

 

쿠키가 적용될 도메인 디폴트가 쿠키가 만들어진 도메인이다

 

secure : true

 

디폴트는 false 다. true로 설정하면 쿠키전송은 https 프로토콜로만 가능

 

raw : true

 

디폴트는 false이다 false 일 경우는 쿠키는 생성되거나 읽을 떄 기본적으로 인코딩/디코딩을 한다(encodeURIComponent / decodeURIComponent 이용)



출처: http://cafe.naver.com/wdprj/6

반응형

'JQuery > JQuery' 카테고리의 다른 글

JQuery Select Box 제어  (0) 2019.09.10