DAY4 추가
- 원래
$()
로 시작하는 onload 대체 함수는 $(document).ready
로 표기한다.
$('#title').text();
$('#content').html();
$('p').attr('class');
$('p').attr('class', 'new_class');
$('#name').val();
$('#name').val('kim');
jQuery - event
- jQuery 문법을 이용하여 이벤트 처리를 할때는 람다 함수(arrow function)를 권장하지 않는다.
- 1.8.x 미만 버전은
live()
도 사용 가능하지만, 1.7.x 버전 이후로는 live()
, bind()
, delegate()
가 모두 on()
으로 통합됐다. on()
또는 ${이벤트 이름}()
함수를 사용하자.
<script>
$(document).ready(() => {
$('#btn_click').click(function () {
console.log('click');
});
});
</script>
<body>
<button id="btn_click"></button>
</body>
- 함수 체이닝 기법으로도 사용 가능하다.
this
키워드로 간편하게 자신에게 접근도 가능하다.
<script>
$(document).ready(() => {
$('#title').mouseenter(function() {
console.log('enter');
$(this).css('background', 'green');
}).mouseleave(function () {
console.log('leave');
$(this).css('background', 'red');
});
$('#title').hover(function() {
console.log('hover in');
}, function() {
console.log('hover out');
});
});
</script>
<body>
<h1 id="title">jQuery</h1>
</body>
- selector가 아닐 떄는
$
이 안붙음에 주의하자.
<script>
$(document).ready(() => {
$('#checkbox').change(function() {
console.log('checkbox: ', this.checked);
});
$('#name').keyup(function() {
console.log('keyup: ', $(this).val());
})
});
</script>
<body>
<input type="checkbox" id="checkbox">정보동의
<input type="text" id="name">
</body>
submit()
이벤트에 return false
를 적어주면 e.stopPropagation()
과 동일하게 작동하며, 로직이 처리되는 것을 기다렸다가 전송하는 기능을 만들 수 있다.
<script>
$(document).ready(() => {
$('#checkbox').change(function() {
console.log('checkbox: ', this.checked);
});
$('#name').keyup(function() {
console.log('keyup: ', $(this).val());
});
$('#test_form').submit(function () {
console.log('test_form');
console.log('name: ', $('#name').val());
console.log('age: ', $('#age').val());
return false;
});
});
</script>
<body>
<form action="jquery02_event2.html" method="get" id="test_form">
<input type="checkbox" id="checkbox">정보동의
<input type="text" id="name">
<input type="number" id="age">
<input type="submit" value="send">
</form>
</body>
- 이벤트를 여러 같은 태그에 할당하려고 할 때, 각자 할당하지 않으면 모두 한번에 실행된다. 이를 막기 위해
each()
함수를 사용한다.
each()
함수를 이용하여 클래스 이름을 부여할 수도 있다. 미리 설정해둔 css가 있다면, css 요소가 적용된다.
<script>
$(document).ready(() => {
$('span').each(function() {
console.log('spans');
$(this).click(function () {
$(this).css('font-size', '32px');
$(this).addClass('bg_span');
});
});
});
</script>
</head>
<body>
<span>aaa</span>
<span>bbb</span>
<span>ccc</span>
<span>ddd</span>
</body>
jQuery - 비동기 통신
$(() => {
$('#test_form').submit(function() {
console.log('submit');
const id = $('#id').val();
const pw = $('#pw').val();
const name = $('#name').val();
const tel = $('#tel').val();
$.ajax({
url: `http://localhost:8090/web02hello/insertOk.do`,
type: "post",
dataType: "json",
data: {
id: id,
pw: pw,
name: name,
tel: tel,
},
success: function(result) {
console.log(result);
}
});
return false;
});
});