IT/jQuery

jQuery button click 이벤트시, each 사용법

노마드오브 2018. 10. 11. 21:38

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>


function func() {

$('div').empty();

var array = [{name: 'naver', link: 'http://naver.com'}, 

{name: 'daum', link: 'http://daum.net'},

{name: 'nate', link: 'http://nate.com'},

{name: 'jquery', link: 'http://jquery.com'}];


// 배열 each(처리할 대상 객체, 처리할 함수) 반복

$.each(array, function (index, item) {

var output = '';

output = '<a href="' + item.link + '">' + item.name + '</a><br>' ;


//document.body.innerHTML += output;

$('div').append(output);

});

}


$(document).ready(function () {

$('button').click(function () {

func();

});

});


</script>

</head>

<body>

<button type="button">버튼</button>

<div></div>

</body>

</html>




<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<style type="text/css">

.high_0 {background-color: yellow;}

.high_1 {background-color: orange;}

.high_2 {background-color: blue;}

.high_3 {background-color: green;}

.high_4 {background-color: red;}

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

$(document).ready(function () {

$('h1').each(function (index, item) {

$(this).addClass('high_' + index);

});

});

</script>

</head>

<body>

<h1>item-0</h1>

<h1>item-1</h1>

<h1>item-2</h1>

<h1>item-3</h1>

<h1>item-4</h1>

</body>

</html>





'IT > jQuery' 카테고리의 다른 글

jQuery - html(), text()  (0) 2018.10.13
jQuery - jQuery를 사용하여 css 적용하는 방법  (0) 2018.10.12
jQuery $('img').attr('src')  (0) 2018.10.12
jQuery 선택자로 css 적용  (0) 2018.10.11
jQuery document ready  (0) 2018.10.10