JQuery [ btnClick ]

양혜정·2024년 4월 21일
0

JQuery 실행

목록 보기
18/42


HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>버튼을 클릭하면 색상이 나오는 것</title>

<link rel="stylesheet" href="css/02.css">

<script type="text/javascript" src="../../js/jquery-3.7.1.min.js"></script>
<script type="text/javascript" src="js/02.js"></script>

</head>
<body>

	<div id="container">
		<div id="btnsDiv"></div>
		<div>
		    <div id="colorDiv"></div>
		    <div id="hangulDiv"></div>
	    </div>
	</div>

</body>
</html>

JS

$(document).ready(function(){

    const arr_btn = [{color:"red", hangul:"빨강"}
                  ,{color:"orange", hangul:"주황"}
                  ,{color:"yellow", hangul:"노랑"}
                  ,{color:"green", hangul:"초록"}
                  ,{color:"blue", hangul:"파랑"}
                  ,{color:"navy", hangul:"남색"}
                  ,{color:"purple", hangul:"보라"}
                 ];

    let html = `<span>버튼을 눌러보세요</span>`;

    arr_btn.forEach(item => {
        html += `<button type='button'>${item.color}</button>`;
    })

    $("div#btnsDiv").html(html);

    $("div#container > div#btnsDiv > button").click(function(e){

        const i =  $("div#container > div#btnsDiv > button").index($(e.target));  
        // console.log(i);
        //  선택자.index(특정엘리먼트); 
        // ==> 선택자가 복수개 엘리먼트를 가리키는 것일때 특정엘리먼트가 복수개 엘리먼트중 몇 번째 index 값을 가지는지를 알려주는 것이다.

        const color = arr_btn[i].color;

        $('div#colorDiv').css({'width':'150px','height':'150px','background-color':`${color}`});
        $('div#hangulDiv').html(`${arr_btn[i].hangul}`);
        $('div#hangulDiv').css({'color': `${color}`});

    })  // end of $("<button>${item.color}</button>").click(function(e){})-------

    // trigger 설정
    $("div#container > div#btnsDiv > button").eq(0).trigger('click');

})      // end of $(document).ready(function(){})-------------------

CSS

@charset "UTF-8";

div#container {
	/* border: solid 1px gray; */
	
	width: 90%;
	margin: 0 auto;
	padding: 2%;
}

div#container > div#btnsDiv > span {
	font-size: 20pt;
	background-color: navy;
	color: white;
	margin-right: 60px;
}

div#container > div#btnsDiv > button {
	font-size: 20pt;
	width: 100px;
	height: 50px;
	margin-right: 20px;
}


div#container > div:nth-child(2) {
	display: flex;
}

div#container > div:nth-child(2) > div {
	border: solid 0px gray;
	margin: 20px 20px 0 0;
}

div#container > div:nth-child(2) > div#hangulDiv {
	font-size: 60pt;
	margin-top: auto;
}

정리

  • jQueryStudy -> 01_eventHandling -> chap06_addClass_removeClass_accordion_tab_SeatReservation -> 02_css_btnClick_color.html, 02.js, 02.css

0개의 댓글

관련 채용 정보