Web/HTML
[days03] 버튼 1. HTML 2. Javascript 3.JQuery
다연
2020. 12. 2. 19:24
반응형
버튼을 클릭하면 경고창을 띄우도록 만든다.
1. HTML로 작성
<button onclick="window.alert('버튼1 클릭')">버튼1</button>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h3 id=""> html의 id 속성</h3>
<button onclick="window.alert('버튼1 클릭')">버튼1</button>
</body>
</html>
글자를 쓰면 그게 경고창에 떠지도록
2-1. <script> - input으로 입력하면 경고창 뜨게
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h3 id=""> html의 id 속성</h3>
<button onclick="window.alert('버튼1 클릭')">버튼1</button>
<input id="msg" value="안녕">
<button onclick="btn2_click()" id="btn2">버튼2</button>
<script>
function btn2_click() {
var message = document.getElementById("msg").value;
window.alert(message);
}
</script>
</body>
</html>
2-2. <script> input을 이용해 밑으로 출력 (경고창이 X)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="ex06_mystyle.css" rel="stylesheet">
</head>
<body>
<h3 id="">html 요소의 id 속성 : 중복되지 않는 고유한 이름(ID), 모든 태그에 사용 가능, [유일]</h3>
<button onclick="window.alert('버튼 클릭')">버튼 클릭</button>
<input id="msg" value="안녕하세요"> <!--input : 사용자가 입력하는 입력 컨트롤 -->
<button onclick="btn1_click()" id="btn1">버튼 클릭</button>
<!-- #demo -->
<div id="demo"></div>
<script> /* 자바스크립트를 사용하는 곳 == style부분에는 css를 사용하는 곳인것 처럼 */
//[js 함수 선언]
function btn1_click(){ //function 함수명(매개변수){}
//요소+속성 id를 사용해 요소 찾기
//입력받은 요소를 찾아가서 value라는 속성값을 담아와야함 => 이때 ID를 사용한다(고유값이니)
var msg= document.getElementById("msg").value;
//입력할 문자열을 담을 공간( var하면 문자 숫자 실수 뭐 다됨)
//window.alert(msg); //js에는 쌍따옴표 + 대소문자 구분
document.getElementById("msg").value=""; //문자 초기화
//1. 경고창 띄워보기 2. demo에 담아보기
document.getElementById("demo").innerText= msg;
//demo에는 value가 없음 => 시작태그와 닫기태그 사이에 집어넣어야 함 innerText
}
</script>
</body>
</html>
3. JQuery를 이용해 수정
자바스크립트보다 제이쿼리쓰는게 쉽고편하고빠르다. (더 많은 기능 구현 가능)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h3 id="">ex04.html을 jquery 사용해서 수정</h3>
<!-- 이러려면 head에 라이브러리가 있어야 함-->
<input id="msg" value="안녕하세요">
<button id="btn1">버튼 클릭</button>
<div id="demo"></div>
<script>
//입력하고 버튼 클릭할때 demo에 찍으려 함
//jquery
$("#btn1").click(function(){ //이 코딩 == document.getElementById("msg").value="";
//window.alert("test"); 1.경고창
$("#demo").text ( $("#msg").val() ); //value가 아니라 val()라는 함수 사용
//2. 밑에 출력
});
</script>
</body>
</html>
반응형