기본 사용법은 $(선택자).메서드(); 이다.
$(document).ready(function() {
// jQuery 코드를 여기에 작성
$('#btn').click(function() {
alert('버튼 클릭!');
});
});
$(function() {
//$(document).ready(function() {} 과 같음
// 더 짧게 쓸 수도 있음!
});
html() / text() 메서드 의 차이
: html()은 태그까지 가져오고 text()는 텍스트만 가져온다.
remove() / empty() 메서드의 차이
: remove()는 요소 자체를 DOM에서 완전히 제거(연결된 이벤트 핸들러도 제거됨)하고 empty()는 요소는 유지하되 내부 모든 자식 요소만 제거하고 이벤트 핸들러는 유지된다.
<input id="melon" type="text" value="abc" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
console.log($('#melon').val());
});
</script>
</head>
<body>
<input id="melon" type="text" value="abc" />
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
위 코드를 꼭 집어넣어야 한다.
안 집어넣었더니 오류남....ㅎㅎ
http://sample.bmaster.kro.kr/contacts?pageno=3&pagesize=10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$.ajax({
type: 'GET', // 요청 방식: GET, POST, PUT, DELETE 등
url: 'http://sample.bmaster.kro.kr/contacts?pageno=3&pagesize=10', // 요청 보낼 URL
dataType: 'json', // 응답 데이터 형식: json, text, html 등
success: function(response) { // 요청 성공 시 실행될 함수
console.log(response);
$(response.contacts).each(function () {
$('#list-table').append(
'<tr>' +
'<td>' + this.no + '</td>' +
'<td>' + this.name + '</td>' +
'<td>' + this.tel + '</td>' +
'<td>' + this.address + '</td>' +
'<td>' + '<img src = "'+ this.photo + '">' + '</td>' +
'<td>' + '<button class="delete-btn">삭제</button>'+ '</td>' +
'</tr>'
);
});
},
error: function(error) { // 요청 실패 시 실행될 함수
console.error('에러 발생:', error);
},
});
$('#list-table').on('click', '.delete-btn', function() {
$(this).parents('tr').remove();
});
});
</script>
</head>
<body>
<table id = "list-table" border = "1">
<tr>
<td>번호</td>
<td>이름</td>
<td>전화번호</td>
<td>주소</td>
<td>사진</td>
<td>삭제</td>
</tr>
</table>
</body>
</html>

$.ajax({
type: 'GET', // 요청 방식: GET, POST, PUT, DELETE 등
url: 'https://example.com/data', // 요청 보낼 URL
data: { key: 'value' }, // 서버에 보낼 데이터 (선택 사항)
dataType: 'json', // 응답 데이터 형식: json, text, html 등
contentType: 'application/json', // 전송할 데이터 형식 (기본값: application/x-www-form-urlencoded)
success: function(response) { // 요청 성공 시 실행될 함수
console.log(response);
},
error: function(error) { // 요청 실패 시 실행될 함수
console.error('에러 발생:', error);
},
complete: function() { // 요청 완료 시(성공/실패 상관없이) 실행될 함수
console.log('요청 완료');
}
});

<body>
<h1>1. +연산</h1>
<input type="number" id="v1" value="10">+
<input type="number" id="v2" value="20">=
<input type="text" id="result" value="">
<button id="btn">연산</button><br>
<br>
<br>
<h1>2. 총합 구하기</h1>
가격<input type="text" id="price" value="2500">X
수량<select id="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
총합:<span id="total"></span>
<hr>
<hr>
<hr>
<h1>3. 총합 구하기2 (선택된 값만)</h1>
<div>
바나나(1000원) <input type="checkbox" name="fruit" class="fruit" value="1000"><br>
사과(500원) <input type="checkbox" name="fruit" class="fruit" value="500"><br>
배(1500원) <input type="checkbox" name="fruit" class="fruit" value="1500"><br>
<button id="btnTotal">총합구하기</button><br>
선택한 총가격:<span id="totalPrice"></span>
</div>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$('#btn').click(function () {
let v1 = $('#v1').val();
let v2 = $('#v2').val();
$('#result').val(parseInt(v1) + parseInt(v2));
});
$('#quantity').change(function() {
let price = $('#price').val()
if (price == '0' || price == "") {
$('#total').text("0");
}
else {
$('#total').text(parseInt(price) * $('#quantity').val());
}
});
let totalPrice = 0;
$('.fruit').change(function() {
if ($(this).is(':checked')) {
totalPrice += parseInt(this.value);
}
else {
totalPrice -= parseInt(this.value);
}
});
$('#btnTotal').click(function() {
$('#totalPrice').text(totalPrice);
});
});
</script>
</head>
<h1>1. +연산</h1>
<input type="number" id="v1" value="10"> +
<input type="number" id="v2" value="20"> =
<input type="text" id="result" value="">
<button id="btn">연산</button><br>
<br><hr><br>
<h1>2. 총합 구하기</h1>
가격 <input type="text" id="price" value="2500"> X
수량
<select id="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
총합 : <span id="total"></span>
<br><hr><br>
<h1>3. 총합 구하기2 (선택된 값만)</h1>
<div>
바나나(1000원) <input type="checkbox" name="fruit" class="fruit" value="1000"><br>
사과(500원) <input type="checkbox" name="fruit" class="fruit" value="500"><br>
배(1500원) <input type="checkbox" name="fruit" class="fruit" value="1500"><br>
<button id="btnTotal">총합구하기</button><br>
선택한 총가격 : <span id="totalPrice"></span>
</div>
</body>
</html>

<input type="text" id="words">
<button type="button" id="add" >추가</button><br>
<ui id="uList"></ui>
<br><br><br>
<input type="text" id="words">
<button type="button" id="add" >추가</button><br>
<ui id="uList"></ui>
<br><br><br>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$('#firstButton').click(function () {
let bodyHtml =
"<button id='secondButton'>두 번째 버튼</button>";
$('#mainDiv').append(bodyHtml);
});
});
</script>
</head>
<body>
<div id="mainDiv">
<button id="firstButton">첫 번째 버튼</button>
</div>
</body>
</html>
A.
첫 번째 버튼에만 마진이 있는 이유는 브라우저의 기본 스타일(기본 CSS) 때문이다.
각 브라우저는 HTML 요소에 기본 스타일을 자동으로 적용하는데 <button> 요소는 보통 외부 여백(margin)이나 내부 여백(padding)을 가지고 있다.
문제는 동적으로 추가된 버튼에는 이 기본 스타일이 완전히 적용되지 않거나 상황에 따라 다르게 작동할 수 있다.
특히 jQuery나 JavaScript로 HTML 요소를 추가할 때 기본 스타일이 다르게 적용될 때가 있다.
해결 방법으로는 스타일을 명시적으로 추가하거나 .css() 메서드 사용해서 두번째 버튼에 스타일을 추가하면 된다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$.ajax({
type: 'GET',
url: 'https://sample.bmaster.kro.kr/contacts?pageno=3&pagesize=10',
success: function(response) {
console.log(response)
$(response.contacts).each(function(index, item) {
$('#list-table').append(
'<tr>' +
'<td>' + item.no + '</td>' +
'<td>' + item.name + '</td>' +
'<td>' + item.tel + '</td>' +
'<td>' + item.address + '</td>' +
'<td>' + '<img src="' + item.photo + '" alt="사진" width="100">' + '</td>' +
'<td>' + '<button class="btnDelete">삭제</button>' + '</td>' +
'</tr>'
);
});
},
error: function(error) {
console.log(error);
},
});
// 삭제 버튼 기능
$('#list-table').on('click', '.btnDelete', function() {
$(this).parents('tr').remove();
});
});
</script>
</head>
<body>
<table id="list-table" border="1">
<tr>
<th>번호</th>
<th>이름</th>
<th>전화번호</th>
<th>주소</th>
<th>사진</th>
<th>삭제</th>
</tr>
</table>
</body>
</html>

A. $(this).closest('tr') 또는 $(this).parents('tr')를 쓰는 이유는 버튼을 클릭했을 때 해당 버튼이 속한 테이블 행(row, <tr>) 전체를 제거하기 위해서이다.
<tr>은 테이블의 한 행을 의미하니까 버튼이 클릭되면 해당 행 전체가 사라져야 한다.
만약 <td>만 제거하면 버튼이 있는 칸만 없어지고 나머지 셀들은 남아있어서 레이아웃이 깨지게 된다.
세줄요약:
1.jquery 는 자바스크립트 기반으로 만들어 졌으며, 좀더 쉽게 dom 객체를 다룰수 잇다.
2. 제이쿼리의 val() 함수와 자바스크립트의 value 값을 혼동하지 말자.
3. 제이쿼리의 기본 사용법은 $(‘선택자’).함수() 이다.