버튼 클릭 시 버튼 변경 - beoteun keullig si beoteun byeongyeong


개발하자/jQuery

클릭한 버튼 원하는 값으로 바꾸기

2015. 2. 27. 15:46

<html>
 <head>
 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
 <script>

 $(document).ready(function(){

 $("input").click(function(){
  //this.value="홍길동";
 $(this).val("홍길동");    //인자값 주지 않으면 값을 얻어오는것이고 인자값 주면 셋팅하는 것이다.
 });

 });

 </script>
 </head>
 <body>
 <input type="button" value="aaa">
 <input type="button" value="bbb">
 <input type="button" value="ccc">
 </body>
</html>


id를 지정해준다.

<!DOCTYPE html>

<html>

<head>

<title>자바스크립트</title>

<link rel="stylesheet" type="text/css" href="index.css">

</head>

<body>

<h2 id="title">This Works!</h2>

<script src="index.js">

</script>

</body>

</html>

cs

id="title" 를 가지고 와서 title 상수에 담는다.

handeClick() 함수를 만들어 id="title"을 클릭하면 색상이 blue로 변경되게 한다.

title.요소에 이벤트를 설정하여 클릭을 하면 함수가 실행되게 한다. 

const title = document.querySelector("#title");

// handleResize 함수를 만든다.

function handleClick(){

title.style.color = 'blue';

}  

// id="title" 을 클릭하면 이벤트를 발생시킨다. 

// 이벤트의 내용은 handleClick()함수에 담고 있다.

title.addEventListener("click", handleClick);

cs

텍스트를 클릭하면 색상이 바뀜

버튼 클릭 시 버튼 변경 - beoteun keullig si beoteun byeongyeong

기본색상이 있는 텍스트를 클릭하면 다른색으로 변경 다시 클릭하면 원래색으로 돌아오게하는 방법

직접적으로 css코드를 바꾸는 방법은 좋은 방법이 아니야.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

const title = document.querySelector("#title");

const BASE_COLOR = "red";

const OTHER_COLOR = "blue";

//함수만들어준다.

function handClick(){

const currentColor = title.style.color;

if(currentColor === BASE_COLOR){

title.style.color = OTHER_COLOR;

}else{

title.style.color = BASE_COLOR;

}

}

//초기화값

function init(){

title.style.color = BASE_COLOR;

title.addEventListener("click",handClick);

}

//초기값 실행

init();

cs


텍스트를 클릭을 하면 클래스를 clicked를 넣어주는 방법

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

const title = document.querySelector("#title");

const CLICKED_CLASS = "clicked";

function handClick(){

const hasClass = title.classList.contains(CLICKED_CLASS);

if(hasClass){

title.classList.remove(CLICKED_CLASS);

}else{

title.classList.add(CLICKED_CLASS);

}

}

function init(){

title.addEventListener("click", handClick)

}

init();

cs

위의 코드를 아래의 toggle로 간단하게 변경할 수 있어!

const title = document.querySelector("#title");

const CLICKED_CLASS = "clicked";

function handClick(){

title.classList.toggle(CLICKED_CLASS);

}

function init(){

title.addEventListener("click", handClick)

}

init();

cs