jquery-9: each
$('a').each(function(each,node){
$(node).text(index);
})
- a 하나하나를 꺼내서 함수를 적용시키겠다
- a의 첫번째 element가 node 첫번째로 들어가고 index는 0이됨
- a의 두번째 element가 node 두번째로 들어가고 index는 1이됨
data-bg-color
- 유저가 직접 만든 속성 앞에는
data
를 붙여주는게 관례
<section>
<div data-click-class="a"></div>
<div data-click-class="b"></div>
<div data-click-class="c"></div>
</section>
<button>버튼</button>
section > div.a {
width: auto;
height: 100px;
margin: 20px;
background-color: gold;
}
section > div.b {
width: 50px;
height: 300px;
margin: 50px;
background-color: green;
}
section > div.c {
width: 700px;
height: 400px;
margin: 80px;
background-color: blue;
}
$("button").click(function () {
$("section > div").each(function (index, node) {
let className = $(node).data("click-class");
$(node).toggleClass(className);
});
});
- 서로 다른 설정값을 가질 때 사용하기 좋음
- 참고 ```js // $(“button”).click(function () { // $(“section > div”).each(function (index, node) { // //값 가져오기 // let bgColor = $(node).data(“bg-color”); // let width = $(node).data(“width”); // let height = $(node).data(“height”);
// //값 적용하기 // if (bgColor) { // $(node).css(“background-color”, bgColor); // }
// if (height) { // $(node).css(“height”, height); // }
// if (width) { // $(node).css(“width”, width); // }
// //값 텍스트에 쓰기 // $(node).text(index + “ : “ + bgColor); // }); // }); ```
댓글남기기