JQuery

211001_each,append,after

요옫 2021. 10. 1. 15:51

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

<style type="text/css">

.bg_0{

    background-color: orange;

    color: gray;

}

 

.bg_1{

    background-color: lavender;

    color: purple;

}

 

.bg_2{

    background-color: blue;

    color: white;

}

 

.bg_3{

    background-color: green;

    color: white;

}

 

.bg_4{

    background-color: pink;

    color: red;

}

 

ul li {

width: 130px;

}

</style>

 

</head>

<body>

<!-- each는 주로 태그 반복할때 사용 -->

<b></b><b></b><b></b><b></b><b></b>

 

<script type="text/javascript">

//b태그 개수만큼 자동반복

//i는 index 0부터

//element는 인덱스에 해당하는 b태그..생략가능

$("b").each(function(i, element) {

$(this).text(i);

//$(element).text(i);  같은 방법

});

</script>

 

<hr>

 

<ul>

  <li>peach</li>

  <li>banana</li>

  <li>kiwi</li>

  <li>strawberry</li>

  <li>orange</li>

</ul>

 

 

<script type="text/javascript">

$("ul li").each(function(idx) {

//each는 선택요소가 여러개일때 각각에 대해 반복하여 함수 실행

$(this).addClass("bg_"+idx);  //bg_0~4

});

 

 

//append추가, after로 추가할 때 비교

//li에 마우스 올리면 ***출력

$("ul li").mouseover(function() {

//$(this).append("<b>***</b>");

 

$(this).after("<b>***</b>");  //li태그 뒤에 b태그가 추가

});

 

 

//벗어나면 b태그 지우기

$("ul li").mouseout(function() {

$(this).next().remove();

});

</script>

</body>

</html>

 

마우스 올렸을 때 --> 마우스 뺐을 때