Web/jQuery
[days02] 복습 - 1) 콜백함수 / 2) $.each()
다연
2020. 12. 21. 13:47
반응형
1. 콜백함수
매개변수로 전달되는 함수
<script>
//함수 선언
function callTenTimes(callback) {
for (var i = 0; i <10; i++) {
callback(); //매개변수로 전달된 함수 호출
}
}
//변수 선언
var callback = function() {
alert("함수 호출");
}
callTenTimes(callback);
</script>
함수 호출 alert가 10번 반복 출력된다.
콜백 함수는 익명 함수로 사용할 때가 많다. 매개변수에 익명함수를 곧바로 입력할 수도 있다는 것을 기억하자.
<script>
//함수 선언
function callTenTimes(callback) {
for (var i = 0; i <10; i++) {
callback(); //매개변수로 전달된 함수 호출
}
}
callTenTimes(function() {
alert("함수 호출");
});
</script>
2. $.each
알아둘 것
jQuery()는 jQuery 라이브러리의 기본 함수라 많이 사용하며, 쉽게 사용할 수 있도록 다음 코드와 같이 변수를 대치한다.
window.jQuery == window.$ == jQuery == $
$.add(url, data, callback, type); //jquery가 가진 메소드라는 의미 $.메소드()
$.each() == jQuery.each
jQuery 객체를 반복하여 일치하는 각 요소에 대해 함수를 실행
<body>
<ul>
<li>Lorem.</li>
<li>Aliquam.</li>
<li>Quia?</li>
<li>Nihil!</li>
<li>Non.</li>
</ul>
<script>
$(function(){
/*
$("li").each(function(index) { //li태그를 하나하나 반복하겠다
console.log(index+":"+$(this).html()); //그 안의 글자
})
*/
$.each($("li"), function(i, elt) {
console.log(i+"/"+elt.innerHTML); // elt.html() 불가 (요소이지 html 객체가 아니기 때문)
});
});
</script>
</body>
해당 div를 클릭하면 그 div의 style속성이 출력되도록 한다.
![]() |
![]() |
![]() |
![]() |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
div {
height: 50px;
margin: 5px;
padding: 5px;
float: left;
}
#box1 {
width: 50px;
color: yellow;
background-color: blue;
}
#box2 {
width: 80px;
color: rgb(255, 255, 255);
background-color: rgb(15, 99, 30);
}
#box3 {
width: 40px;
color: #fcc;
background-color: #123456;
}
#box4 {
width: 70px;
background-color: #f11;
}
</style>
</head>
<body>
<p id="result"> </p>
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<script>
$( "div" ).click(function() {
//html 문자열을 저장할 변수
var html = [ "The clicked div has the following styles:" ];
//[] : 배열 (여러 개의 스타일 속성을 css() 함수로 얻어올 때) -> styleProps 저장
var styleProps = $( this ).css([
"width", "height", "color", "background-color"
]);
//타입 object -> array
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value ); //배열 추가 : push()
});
//배열 join()
$( "#result" ).html( html.join( "<br>" ) );
});
</script>
</body>
</html>
반응형