1. 동적 추가 메뉴 만들기 (jQuery) BONUS(Javascript버전(2))
- 추가: input에 입력된 메뉴명을 선택한 Row 하단에 추가
- 수정: 선택한 Row의 메뉴명을 input에 입력한뒤 수정버튼을 클릭하면 메뉴명 수정처리
- 삭제: 선택한 메뉴명 삭제
- UP: 선택한 Row를 상단으로 이동
- DOWN: 선택한 Row를 하단으로 이동
////0. jQuery버전 - 강사님 답
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<style>
body {
font-size: 9pt;
font-family: "굴림";
}
div, p, ul, li {
}
ul.menu {
padding: 10px;
list-style: none;
border: 1px #000 solid;
}
ul.menu li {
border: 1px #eeeeee solid;
margin: 10px;
}
li.select {
background-color: #ccc;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
// 전역 변수 선언 및 초기화
var $menu = null;
var $menuName = null;
var $selectedItem = null;
$(document).ready(function() {
init();
initEvent();
});
// 전역에서 사용할 요소 초기화
function init() {
$menu = $("ul.menu");
$menuName = $("#menuName");
}
// 이벤트 초기화
function initEvent() {
// 메뉴 추가
$("#add").click(function() {
addMenu();
})
$menu.on("click", "li", function() {
selectItem($(this));
})
// 업데이트
$("#update").click(function() {
updateMenuItem();
})
// 선택 항목 삭제
$("#remove").click(function() {
removeMenuItem();
})
// 선택 메뉴 항목을 위로 이동
$("#up").click(function() {
upMenuItem();
})
// 선택 메뉴 항목을 아래로 이동
$("#down").click(function() {
downMenuItem();
})
}
// 메뉴 추가 처리
function addMenu() {
// 텍스트 입력 값 구하기
var menuName = $menuName.val();
// 신규 메뉴 아이템 문자열 만들기
var newMenuItem = "<li>" + menuName + "</li>";
// 선택 메뉴 아이템이 있는 경우 신규 메뉴 아이템을 선택 메뉴 아이템 아래에 추가
if ($selectedItem) {
$selectedItem.after(newMenuItem);
} else {
// 메뉴에 신규 메뉴 아이템 추가
$menu.append(newMenuItem);
}
}
// 메뉴 선택 처리
function selectItem($item) {
// 기존 선택 메뉴 아이템이 있는 경우 선택 효과 제거
if ($selectedItem != null)
$selectedItem.removeClass("select");
// 신규 선택 메뉴 아이템 처리
$selectedItem = $item;
$selectedItem.addClass("select");
}
// 메뉴 항목 이름 수정 하기
function updateMenuItem() {
if ($selectedItem) {
var menuName = $menuName.val();
$selectedItem.html(menuName);
} else {
alert("선택 메뉴가 존재 하지 않습니다.")
}
}
// 선택 메뉴 항목 삭제
function removeMenuItem() {
if ($selectedItem) {
$selectedItem.remove();
$selectedItem = null;
} else {
alert("선택 메뉴가 존재 하지 않습니다.")
}
}
// 위로 이동
function upMenuItem() {
if ($selectedItem) {
var $prevItem = $selectedItem.prev();
if ($prevItem)
$selectedItem.insertBefore($prevItem);
} else {
alert("선택 메뉴가 존재 하지 않습니다.")
}
}
// 아래로 이동
function downMenuItem() {
if ($selectedItem) {
var $nextItem = $selectedItem.next();
if ($nextItem)
$selectedItem.insertAfter($nextItem);
} else {
alert("선택 메뉴가 존재 하지 않습니다.")
}
}
</script>
</head>
<body>
<div>
<input type="text" id="menuName" />
<button id="add">
추가
</button>
<button id="update">
수정
</button>
<button id="remove">
삭제
</button>
<button id="up">
UP
</button>
<button id="down">
DOWN
</button>
</div>
<ul class="menu">
</ul>
</body>
</html>
-------------------------------------------------
////1. jQuery버전 - table버전
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="append_row">
<button type="button" id="add_menu">추가</button>
<input type="button" id="alter_menu" value="수정">
<input type="button" id="remove_menu" value="삭제">
<input type="button" id="up_menu" value="UP">
<input type="button" id="down_menu" value="DOWN">
<br>
<br>
<!-- 동적 테이블 -->
<table border="1" id="list_table" style="cursor:pointer">
<colgroup>
<!-- column 의 설정을 할수 있다. -->
<col style="width: 100px;">
</colgroup>
<tr><th>Menu</th></tr>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('#list_table').on("click", "tr", function() { //table의 tr을 클릭했을 때
tableid = $(this).attr('id'); //선택한 tr의 table id를 받아온다.
// alert($(this).attr('id'));
$("#append_row").val($("#" +tableid).text()); //
});
var cnt = 0; //추가
$('#add_menu').on(
"click",
function() { //add_menu버튼을 눌렀을 때
$('#list_table').append( //table의 가장 아래에 값이 추가되도록 한다.
$('<tr id='+cnt+'>').append( //여기서 cnt는 0부터 들어간다
$('<td>').append($('#append_row').val()),
));
cnt += 1; //추가가 되면 cnt는 1이 증가한다.
$('#append_row').val('');
});
$("#alter_menu").on("click",function(){ //수정
$('#'+tableid).html($("#append_row").val());
});
$('#remove_menu').on("click", function() { //삭제
$('#' + tableid).remove();
});
$('#up_menu').on("click", function() { //table list up
$('#' + tableid).insertBefore($('#' + tableid).prev());
});
$('#down_menu').on("click", function() { //table list down
$('#' + tableid).insertAfter($('#' + tableid).next());
});
});
</script>
</body>
</html>
----------------------------------------------------------------------
////1-1. jQuery - list버전
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
ul{
list-style-type:none;
padding-left:0px;
border : 1px solid black;
width:420px;
}
li{
padding: 5px 0px 5px 5px;
margin-bottom: 5px;
border-bottom: 1px solid white;
font-size: 30px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#ul_list').on("click","li",function() { //ul 아이디 ul_list에서 li를 클릭했을때
listId = $(this).attr('id'); //ul_list에서 텍스트에 해당하는 id를 가져옴
});
});
var idcnt=0; //리스트에 추가되는 index값을 0으로 초기화한다.
function add_menu(){
var text = $("#text").val(); //텍스트 입력값
var ul_list = $("#ul_list"); //ul_list
ul_list.append("<li id="+idcnt+">"+$('#text').val()+"</li>"); //li id의 값을 하나씩 증가시켜 저장하고 텍스트를 li 리스트에 추가 저장
idcnt++; // 추가 될 때마다 id의 값 하나씩 증가
}
function alter_menu(){
$("#"+listId).html($("#text").val()); //listid에 저장되어 있는 값을 #text로 새로 입력된 값과 변경
};
function remove_menu(){ //listid에 저장되어 있는 아이디의 값에 해당하는 텍스트 삭제
$("#"+listId).remove()
};
function up_menu(){
$("#"+listId).insertBefore($("#"+listId).prev()); //listid에 저장되어 있는 선택한 아이디의 값과 이전의 값과 위치를 변경
}
function down_menu(){
$("#"+listId).insertAfter($("#"+listId).next()); //listid에 저장되어 있는 선택한 아이디의 값보다 큰 값과 위치를 변경
}
</script>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type = "text" name="text" id="text"/>
<input type = "button" id="insert" onclick="add_menu()" value="추가" />
<input type = "button" id="update" onclick="alter_menu()" value="수정"/>
<input type = "button" id="delete" onclick="remove_menu()" value="삭제"/>
<input type = "button" id="up" onclick="up_menu()" value="UP"/>
<input type = "button" id="down" onclick="down_menu()" value="DOWN"/>
<ul id="ul_list" style="cursor:pointer">
</ul>
</body>
</html>
----------------------------------------------------------------------
////2. javaScript버전
<!DOCTYPE html>
<html>
<head>
<title>Add Edit Remove HTML Table Row</title>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<div class="tab tab-2">
<input type="text" name="menu" id="menu">
<button onclick="add_menu();">추가</button>
<button onclick="alter_menu();">수정</button>
<button onclick="remove_menu();">삭제</button>
<button onclick="upNdown('up');">UP</button>
<button onclick="upNdown('down');">DOWN</button>
</div>
</div>
<br>
<div class="tab tab-1">
<table id="table" border="1" style="cursor: pointer">
<tr>
<th>MENU</th>
</tr>
</table>
</div>
<script>
var rIndex, table = document.getElementById("table"); // html의 아이디가 table인 태그를 rIndex, table 넣어준다.
function checkEmptyInput() { // input 값이 empty인지 확인
var isEmpty = false, // input 값이 empty이면 false
menu = document.getElementById("menu").value; //html의 아이디가 menu인 태그의 값을 menu에 넣어준다
if (menu === "") {
alert("Menu Empty"); //input값이 비어 있으면 alert로 "Menu Empty"가 뜨게 한다.
isEmpty = true;
}
return isEmpty;
}
function add_menu() { // 메뉴 추가
if (!checkEmptyInput()) { //input 값이 empty인지 확인한다
var newRow = table.insertRow(table.length), //새로운 행을 만들어 추가한다.
cell1 = newRow.insertCell(0), menu = document
.getElementById("menu").value; //input 값을 메뉴에 담는다.
cell1.innerHTML = menu; //menu를 html에 뿌려준다.
selectedRowToInput(); //행이 추가 될때 함수를 설정해준다.
}
}
function selectedRowToInput() { //input text에 입력한 값을 테이블에서 선택하면 보여준다.
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
rIndex = this.rowIndex; // 선택된 행의 인덱스를 가져온다
document.getElementById("menu").value = this.cells[0].innerHTML;
};
}
}
selectedRowToInput();
function alter_menu() { //수정
var menu = document.getElementById("menu").value;
if (!checkEmptyInput()) {
table.rows[rIndex].cells[0].innerHTML = menu;
}
}
function remove_menu() { //삭제
table.deleteRow(rIndex);
document.getElementById("menu").value = ""; // input text값을 삭제 한다.
}
var index = 0; // 선택된 행 인덱스를 설정하는 변수
function getSelectedRow() {
var table = document.getElementById("table");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
if (typeof index !== "undefined") { // 이전에 선택한 행에서 선택한 항목을 지운다
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction) {
var rows = document.getElementById("table").rows, parent = rows[rIndex].parentNode;
if (direction === "up") {
if (rIndex > 1) { //index값이 1보다 클 때 실행
parent.insertBefore(rows[rIndex], rows[rIndex - 1]);// up을 누르면 선택한 인덱스 값은 -1이 된다.
rIndex--; //인덱스 값을 -1을 해준다
}
}
if (direction === "down") {
if (rIndex < rows.length - 1) { //선택한 인덱스 값이 전체 row보다 작으면 down을 실행
parent.insertBefore(rows[rIndex + 1], rows[rIndex]); //down을 누르면 선택한 인덱스 값은 +1이 된다.
rIndex++; //인덱스 값을 +1을 해준다.
}
}
}
</script>
</body>
</html>
2. DOM을 이용해 HTML 요소를 간단하게 만들어주는 make 함수 (Javascript)
function make(tagname, attributes, children)
- tagname: tag이름
- attributes: optional, 객체, 프로퍼티와 값
- children: optional, 요소에 추가할 자식, string/element/element배열
///////////////// 주어진 문제만 처리가능한 유틸 version!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DOM을 이용해 HTML 요소를 간단하게 만들어주는 make 함수</title>
</head>
<script type="text/Javascript">
//문제
function ex1(){
var body = document.getElementsByTagName('body')[0];
var div = make("div", {'style':'background-color:red;', 'id':'div1'}, "hello world");
body.appendChild(div);
var tds = [make("td",{},"Name"), make("td",{},"Type"), make("td",{},"Value")];
var tr = make("tr",{}, tds);
var table = make("table", {'style':'border: 1px solid red;'}, tr);
body.appendChild(table);
}
// tagname: tag이름
// attributes: optional, 객체, 프로퍼티와 값
// children: optional, 요소에 추가할 자식, string/element/element배열
function make(tagname, attributes, children){
var td = document.createElement('td'); // 전역변수로 사용하기 위해 선언
var tr = document.createElement('tr');
//tag name이 div일경우
if(tagname == "div"){
var tag = document.createElement(tagname); // tagname값 받아 div생성
tag.setAttribute("style",attributes.style); // style적용
tag.setAttribute("id", attributes.id); // id 적용
if(typeof children == 'string'){ // object이면 (객체인지 일반 String type인지 체크해서 거르기!)
var text = document.createTextNode(children); // text노드만들기
tag.appendChild(text);
} else { // string이면
tag.innerHTML = children; // children 값 tag에 넣음
}
return tag;
//tagname이 tr, td 일경우
}else if(tagname == "td" || tagname == "tr"){ // tr, td생성
var tag = document.createElement(tagname); // tagname값 받아 tr, td생성
tag.innerHTML = children; // tr : <tr><td>Name</td>,<td>Type</td>,<td>Value</td></tr>
return tag.outerHTML; // inner가 아닌 outer로 tag까지 포함하도록 리턴.
// tagname이 table 일 경우
} else {
var tag = document.createElement(tagname); // tagname값 받아 table생성
tag.setAttribute("style",attributes.style); // style적용
tag.setAttribute("id", attributes.id); // id적용
var n_child = children.replace(/,/gi, ""); // replaceAll 효과 , /,/gi -> 정규식
tag.appendChild(tr); // table에 tr appendChild
tag.innerHTML = n_child; // innerHTML : html요소의 안쪽값을 n_child로 한다.
return tag; //table 리턴위해 tag만 리턴.
}
}
</script>
<body>
<div>
<button onClick="ex1()">출력</button>
</div>
</body>
</html>
------------------------------------------
///////////////// 모든 tag 처리가능한 유틸 version!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
table {
width: 100%;
border: 1px solid #333333;
}
td {
padding: 10px;
border: 1px solid #333333;
}
.a {
border-collapse: separate; /* 간격존재 */
/*border-collapse: collapse; */ /* 간격제거 */
}
</style>
<script>
// 주어진 tagname과 attributes, children을 사용하여 HTML 엘리먼트를 생성한다
// - tagname: Tag이름
// - attributes: 객체, 프로퍼티 이름과 값, optional
// - children: string/element/element배열, 엘리먼트에 추가할 자식, optional
// 예) make("p", {border:1}, "<tr><td>11</td><td>22</td></tr>")
function make(tagname, attributes, children){
// 두 개의 전달인자를 사용하여 호출했다면, attributes 전달인자는 배열이거나 문자열이다
// 이 경우 children 전달인자는 attributes가 되어야 한다
if(arguments.length == 2 &&
(attributes instanceof Array || typeof attributes == "string")){
children = attributes;
attributes = null;
}
// 엘리먼트를 생성한다
var e = document.createElement(tagname);
// 어트리뷰트를 설정한다
if(attributes){
for(var name in attributes) e.setAttribute(name, attributes[name]);
}
// children이 주어졌으면 이를 추가한다
if(children != null){
if(children instanceof Array){
for(var i = 0; i < children.length; i++){
var child = children[i];
if(typeof child == "string") // 텍스트 노드를 처리
child = document.createTextNode(child);
e.appendChild(child); // 다른 것들은 Node가 아니라고 가정
}
}
else if(typeof children == "string") // 단일 텍스트 자식을 처리
e.appendChild(document.createTextNode(children));
else e.appendChild(children); // 그 외 단일 자식을 처리한다
}
return e; // 엘리먼트 반환
}
// 주어진 태그를 위해 make()를 호출하는 함수를 반환
// var table = maker("table");
function maker(tag){
return function(attrs, kids){
if(arguments.length == 1) return make(tag, attrs);
else return make(tag, attrs, kids);
}
}
function test(){
var body = document.getElementsByTagName('body')[0];
var div = make("div", {'style':'background-color:red;', 'id':'div1'}, "hello world");
body.appendChild(div);
var tds = [make("td",{},"Name"), make("td",{},"Type"), make("td",{},"Value")];
var tr = make("tr",{}, tds);
var table = make("table", {'style':'border: 1px solid red;'}, tr);
body.appendChild(table);
}
</script>
</head>
<body onload="test()">
</body>
</html>
3-1. 이진탐색트리 알고리즘
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Node(data, left, right) { //각 노드는 2개의 자식노드를 가짐
this.data = data; //노드의 값
this.left = left; //노드의 작은자식
this.right = right; //노드의 큰자식
}
function BSTree() { //이진트리함수
this.root = null; //트리의 뿌리노드(1개만 존재)
this.insert = insert; //노드추가
this.inOrderSearch = inOrderSearch; //전위
this.preOrderSearch = preOrderSearch; //중위
this.postOrderSearch = postOrderSearch; //후위
this.min = findMin; //최소값
this.max = findMax; //최대값
}
function insert(data) { //삽입
var node = new Node(data, null, null); //노드 인스턴스 생성
if (this.root == null) {
this.root = node; //뿌리 노드가 없을 시 새로운 노드가 뿌리가 됨
} else {
var current = this.root; //뿌리부터 시작하여 current data값과 들어온 data값을 비교함
var parent;
while (true) { //자식이 없을 때 까지 반복
parent = current;
if (data < current.data) { //들어온 data가 더 작을 때
current = current.left;
if (current == null) {
parent.left = node;
break;
}
} else { //들어온 data가 더 클 때
current = current.right;
if (current == null) {
parent.right = node;
break;
}
}
}
}
}
//중위
function inOrderSearch(printNode) {
inOrder(tree.root, printNode);
}
function inOrder(node, printNode) {
if (node != null) {
inOrder(node.left, printNode);
printNode(node.data + ' ');
inOrder(node.right, printNode);
}
}
//전위
function preOrderSearch(printNode) {
preOrder(tree.root, printNode);
}
function preOrder(node, printNode) {
if (node != null) {
printNode(node.data + ' ');
preOrder(node.left, printNode);
preOrder(node.right, printNode);
}
}
//후위
function postOrderSearch(printNode) {
postOrder(tree.root, printNode);
}
function postOrder(node, printNode) {
if (node != null) {
postOrder(node.left, printNode);
postOrder(node.right, printNode);
printNode(node.data + ' ');
}
}
//최소값
function findMin() { //가장 왼쪽에 있는 data를 가져옴
var current = this.root;
while (current.left != null) {
current = current.left;
}
return current.data;
}
//최대값
function findMax() { //가장 오른쪽에 있는 data를 가져옴
var current = this.root;
while (current.right != null) {
current = current.right;
}
return current.data;
}
var tree = new BSTree();
tree.insert(11);
tree.insert(7);
tree.insert(15);
tree.insert(5);
tree.insert(3);
tree.insert(9);
tree.insert(8);
tree.insert(10);
function printNode(value) {
console.log(value);
}
console.log('*** 중위 순회 ***');
tree.inOrderSearch(printNode);
console.log('*** 전위 순회 ***');
tree.preOrderSearch(printNode);
console.log('*** 후위 순회 ***');
tree.postOrderSearch(printNode);
console.log('********* 최대/최소값 ***********');
console.log(tree.max());
console.log(tree.min());
</script>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
3-2. 하노이 알고리즘
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
//스택 생성자 함수
function Stack(n) {
this.name = n
this.dataStore = []; //스택요소를 저장하는 배열
this.top = 0;
this.push = function push(element) {
this.dataStore[this.top++] = element; //현재 top위치에 새요소를 추가한 다음 top이 증가
};
this.pop = function pop() {
return this.dataStore[--this.top]; //스택의 탑 위치에 있는 요소를 반환한 다음 top변수를 감소
};
this.length = length;
}
var source = new Stack('A'); // A
var helper = new Stack('B'); // B
var dest = new Stack('C'); // C
source.push(3);
source.push(2);
source.push(1); //3 2 1
var string = "";
function towerOfHanoi(n, source1, helper1, dest1) { //하노이 알고리즘 기본원리는
if (n === 1) { //n-1개의 데이터를 A->B로 옮긴 후
string+=source1.name+"->"+dest1.name+" // ";
dest.push(source1.pop()); //1개의 데이터를 A->C로,
} //다시 n-1개를 B->C 옮김
else {
towerOfHanoi(n - 1, source1, dest1, helper1); //재귀함수로 호출
string+=source1.name+"->"+dest1.name+" // ";
dest.push(source1.pop());
towerOfHanoi(n - 1, helper1, source1, dest1);
}
}
towerOfHanoi(3, source, helper, dest);
console.log(string);
</script>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
4. 달력 그리기
<HTML>
<HEAD>
<meta charset="UTF-8">
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
// 시간을 읽어와서 '오전/오후 시:분' 형태로 구해주는 함수
function get_Time(){
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var ampm;
if(hour >= 12){
hour -= 12;
ampm = "오후";
}
else{
ampm = "오전";
}
hour = (hour == 0) ? 12 : hour;
if (minute < 10)
minute = "0" + minute;
return ampm + hour + ":" + minute;
}
// 년과 월을 받아서 마지막 일을 계산해주는 함수
function get_Day(year, month){
var Last_Mon = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var Mon2;
// ==>윤년 체크
if (year % 4 == 0)
Mon2 = true;
if (year % 100 ==0)
Mon2=false;
if (year % 400 ==0)
Mon2=true;
Last_Mon[1] = (Mon2) ? 29 : 28;
return Last_Mon[month];
}
// table을 이용하여 달력을 만들어 줍니다.
function drawCal(firstDay, lastDate, date, year, monthName)
{
var text = "";
text += "<CENTER>";
text += "<TABLE>";
text += "<TH COLSPAN=7 BGCOLOR=#FFFFCC>";
text += "<FONT COLOR=midnightblue SIZE=+3 >";
// 년과 월을 출력합니다.
text += year + "년 " + (monthName + 1) + "월";
text += "</FONT>";
text += "</TH>";
var openCol = "<TD BGCOLOR=#FFEEFF WIDTH=45 HEIGHT=40> ";
openCol += "<FONT COLOR=darkblue> ";
var closeCol = "</FONT></TD>";
text += "<TR ALIGN=center VALIGN=center>";
var weekDay = new Array("일", "월", "화", "수", "목", "금", "토");
// 달력의 일, 월, 화, 수, 목, 금, 토, 일을 출력합니다.
for (var dayNum = 0 ; dayNum <= 6 ; dayNum++)
text += openCol + weekDay[dayNum] + closeCol;
text += "</TR>";
var digit = 1; // Drawing중인 달력의 현재위치
var curCell = 1;
// 달력 표를 만들어 줍니다.
for (var row = 1 ; row <= Math.ceil((lastDate + firstDay - 1) / 7) ; ++row){ // 주
console.log("주-digit:"+digit);
console.log("주-curCell:"+curCell);
text += "<TR ALIGN=right VALIGN=top BGCOLOR=#FFEFEE>"; // 주의시작
for (var col = 1; col <= 7; col++){ // 일
console.log("일-digit:"+digit);
console.log("일-curCell:"+curCell);
// 마지막주 빈칸을 만들어줌
if (digit > lastDate){
n=(Math.ceil((lastDate + firstDay - 1) / 7))*7-(curCell+lastDate-1);
for(var i=1 ; i<=n ; i++);
text += "<TD> </TD>";
break;
}
// 일이 시작되는 칸을 만들어줌
if (curCell < firstDay){
text += "<TD> </TD>";
curCell++;
}
else{
if (digit == date){
text += "<TD HEIGHT=40>";
text += "<FONT COLOR=Red>";
text += digit;
text += "</FONT><BR>";
text += "<FONT COLOR=purple SIZE=2>";
text += "<CENTER>" + get_Time() + "</CENTER>";
text += "</FONT>";
text += "</TD>";
}
else text += "<TD HEIGHT=40>" + digit + "</TD>";
digit++;
}
}
text += "</TR>";
}
text += "</TABLE>";
text += "</CENTER>";
return text;
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
var now = new Date();
var year = now.getYear();
var month = now.getMonth();
var date = now.getDate();
var my_text;
// 익스플로러가 아니면 '1900'을 'year'에 붙여 줍니다.
if(navigator.userAgent.indexOf("MSIE") == -1)
year= 1900 + year
var firstDayInstance = new Date(year, month, 1);
var firstDay = firstDayInstance.getDay()+1;
firstDayInstance = null;
var days = get_Day(year,month); // 달의 마지막 일을 구합니다.
my_text = drawCal(firstDay, days, date, year, month);
// 최종적으로 만들어진 HTML문서를 브라우저에 출력합니다.
document.write(my_text);
// -->
</SCRIPT>
</BODY>
</HTML>
5. 동적 Tree 메뉴
<HTML>
<HEAD>
<meta charset="UTF-8">
<STYLE>
body
{
background-color: #FFFFFF;
color: #333333;
font-family: "굴림", "Verdana";
font-size:10pt;
line-height:150%;
}
table
{
color: #333333;
font-family: "굴림", "Verdana";
font-size:10pt;
line-height:150%;
}
A:link { font-size:10pt; font-family:"굴림";color:#565656; text-decoration:none; }
A:visited { font-size:10pt; font-family:"굴림";color:#565656; text-decoration:none; }
A:active { font-size:10pt; font-family:"굴림";color:#FF6000; text-decoration:none; }
A:hover { font-size:10pt; font-family:"굴림";color:#FF6000;text-decoration:none; }
</STYLE>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function init(){
//createtree 생성후 div 로 아이디 받아옴
var tree = new CreateTree(document.getElementById('div'));
// 메뉴객체 생성
// name : a 태그에 나타나는 내용
// href : a 태그에 사용될 URL
// icon : 기본 아이콘 대신할 아이콘 URL
// child : 자식배열
//root객체, root객체는 실제로 보이지 않는다
var data = {"name":"name","href":"A링크","target":"target","icon":"","child":[]};
//자식개체를 하나 생성
var childA = {"name":"관리자메뉴","href":"","target":"","icon":"menu02.gif","child":[]};
var childB = {"name":"직원메뉴","href":"","target":"","icon":"menu02.gif","child":[]};
var childC = {"name":"관리자메뉴","href":"","target":"","icon":"menu02.gif","child":[]};
var childD = {"name":"임시메뉴","href":"","target":"","icon":"menu02.gif","child":[]};
//자식1를 자식 배열에 push
data.child.push(childA);
data.child.push(childB);
data.child.push(childC);
data.child.push(childD);
//자식1의 하위개체를 생성
var childA1 = {"name":"부하직원조회","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childA2 = {"name":"결재승인","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childA3 = {"name":"결재내역조회","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childB1 = {"name":"결재신청","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childB2 = {"name":"급여정보조회","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childB3 = {"name":"인사정보조회","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childC1 = {"name":"기준관리","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childC2 = {"name":"근무현황조회","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childC3 = {"name":"평가현황조회","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
var childD1 = {"name":"임시1","href":"https://www.w3schools.com","target":"_blank","icon":"menu01.gif","child":[]};
//자식1의 하위객체 push
childA.child.push(childA1);
childA.child.push(childA2);
childA.child.push(childA3);
childB.child.push(childB1);
childB.child.push(childB2);
childB.child.push(childB3);
childC.child.push(childC1);
childC.child.push(childC2);
childC.child.push(childC3);
childD.child.push(childD1);
//트리에 메뉴객체를 연결
tree.data_init(data);
//트리메뉴를 화면에 보여준다
tree.createView();
}
//CreateTree에서 매게 변수 받아오기
function CreateTree(doc){
//데이터 있는 div 를 doc 에받아옴
var div = doc;
this.data_init = function(data){
for(var i in data.child){
// doc 에 img div 새로 생성
var newDiv = document.createElement("div");
var newImg = document.createElement("img");
//data 객체 에 child 를 불러옴
var c = data.child[i];
newDiv.append(c.name);
newDiv.setAttribute('id',"menu_"+i);
newDiv.setAttribute('href',c.href);
newDiv.setAttribute('child',c.child);
newImg.setAttribute('src',c.icon);
newDiv.prepend(newImg);
var c1 = c.child;
// 자식 배열불러와서
for(var j in c1){
var newDiv2 = document.createElement("div");
var newImg2 = document.createElement("img");
var A = document.createElement("A");
newDiv2.setAttribute('class','toggle'); //토글 될 메뉴들에 toggle 클래스명 추가
A.innerHTML = c1[j].name;
A.setAttribute('href',c1[j].href);
A.setAttribute('target',c1[j].target);
newImg2.setAttribute('src',c1[j].icon);
newDiv2.innerHTML=" ";
newDiv2.append(newImg2);
newDiv2.append(A);
newDiv.append(newDiv2);
}
div.append(newDiv);
}
//토글속성 삽입을 위하여 생성
for(var i in data.child){
new toggleMenu(i);
}
}
//페이지 로딩시 토글메뉴 hide 처리
this.createView = function(){
$('.toggle').hide();
}
}
//아이콘 클릭시 토글아이콘 변경
function toggleImg(menu){
if($(menu).attr('src')=='menu02.gif'){
$(menu).attr('src', 'menu03.gif');
}else if($(menu).attr('src')=='menu03.gif'){
$(menu).attr('src', 'menu02.gif');
}
}
//클릭시 toggle클래스들에 토글기능 추가
function toggleMenu(index){
console.log(index);
$("#menu_"+index+">img").click(function(){
toggleImg("#menu_"+index+">img");
$("#menu_"+index+">.toggle").toggle('slow');
});
}
</script>
</HEAD>
<BODY OnLoad="init()">
<DIV ID="div"></DIV>
</BODY>
</HTML>
'Bitcamp > BITCAMP - Front Web' 카테고리의 다른 글
6일차 JavaScript (0) | 2020.07.15 |
---|---|
IBSheet 그리드 특강 (0) | 2019.09.26 |
12일차 jQuery (0) | 2019.09.16 |
11일차 jQuery (0) | 2019.09.11 |
JavaScript - LinkedList, nodeType(재귀), Event 핸들러, DOM (0) | 2019.09.10 |