본문 바로가기

카테고리 없음

jQuery의 디테일

jQuery란? 

HTML의 요소들을 조작하는, 편리한 Javascript를 미리 작성해둔 것. 

1) 코드가 복잡하고, 2) 브라우저 간 호환성 문제도 고려해야해서, jQuery라는 라이브러리가 등장!

 

$('#element').hide();

 

jQuery를 쓰려면 누가 대신 써준 코드를 '임포트' 해야한다.

*임포트: 미리 작성된 Javascript 코드를 가져오는 것

 

어디서?

https://www.w3schools.com/jquery/jquery_get_started.asp

 

jQuery Get Started

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

만약 jQuery를 매번 다운로드하거나 직접 호스팅하기 귀찮다면: jQuery CND을 활용하자.

 

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

 

 

jQuery는 파이참에서 어디에 어떻게 넣어야할까?

: <head> 와 </head> 사이에 <script src = "https:// ______" ></script> 이렇게 넣기!

 

 

css할때도 class 라고 특정 그룹을 가리키고 조작한 것처럼,

JQuery도 id 값을 통해 특정 버튼/인풋박스/div/.. 등을 가리켜야함.

 

예시)

input값 가져오기

<div class="posting-box">
    <div class="form-group">
        <label for="exampleInputEmail1">아티클 URL</label>
        <input id="post-url" type="email" class="form-control" aria-describedby="emailHelp"
            placeholder="">
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">간단 코멘트</label>
        <input type="password" class="form-control" placeholder="">
    </div>
    <button type="submit" class="btn btn-primary">기사 저장</button>
</div>

 

Hide 기능을 통해 특정 div 를 숨길 수 있음.

// 크롬 개발자도구 콘솔창에 쳐보기
// id 값이 post-box인 곳을 가리키고, hide()로 안보이게 한다.(=css의 display 값을 none으로 바꾼다)
$('#post-box').hide();

// show()로 보이게 한다.(=css의 display 값을 block으로 바꾼다)
$('#post-box').show();

 

jQuery를 통해 할 수 있는 것들:

 

예시)

temp_html 은 .append(temp_html); 로 붙이기.

function q3() {
    // 1. input-q3 값을 가져온다.
    let newName = $('#input-q3').val();
    if (newName == '') {
        alert('이름을 입력하세요');
        return;
    }
    // 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${가져온 값}</li>`)
    let temp_html = `<li>${newName}</li>`;
    // 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
    $('#names-q3').append(temp_html);
}

function q3_remove() {
    // 1. names-q3의 내부 태그를 모두 비운다.(jQuery의 $('....').empty()를 이용하면 굿!)
    $('#names-q3').empty();