JavaScript 자동 생성 Grid 만들기(HTML5 Grid, JavaScript Grid, JavaScript 라이브러리 만들어 보기)
JavaScript를 이용하여 Grid를 자동으로 만들어 주는 라이브러리를 만들어 보았습니다.
간단하게 그리드를 생성하는 함수와 그리드를 클릭했을 때 발생되는 이벤트(콜백함수)를 처리까지 어떻게 이루어지는지
간단하게 알아보도록 하겠습니다.
HTML5 호출방식 처리
CSS
div.OY_UI_Item {
width: 100%;
height: 400px;
}
HTML5
<div class="OY_UI_Item">
<div id="myOYGrid"></div>
</div>
위 HTML5 태그를 호출하면 해당 위치에 그리드를 그려줍니다.
OYGrid.create("myOYGrid", option, jsonData);
JavaScript에서 위 함수를 호출하면 드리드의 옵션과 데이터를 주입시킵니다.
첫 번째 매개변수는 div class의 id (어떤 그리드에 만들 것인가)와 그리드 옵션 설정 및 데이터 처리의 경우 JsonArray로 처리하였습니다.
JavaScript - common.js
Grid의 Create 함수, 그리드 생성 또는 이벤트를 생성합니다.
const OYGrid = {
create : function(id, option, jsonData){
let htmlId = document.getElementById(id);
let html = '';
let width = "auto";
let height = "auto";
if(option.width != null && option.width != ""){
width = option.width;
}
if(option.height != null && option.height != ""){
height = option.height;
}
let gridSize = 'style="width:'+width+'; height:'+height+'"';
// grid div
html += '<div class="OY_UI_Grid" '+gridSize+'>';
// grid head
html += '<div class="OY_UI_Head">';
html += '<div class="OY_UI_Rows">';
// column create
for(let i = 0; i < option.column.length; i++){
let colStyle = '';
if(option.column[i].columnTextAlignOption != null && option.column[i].columnTextAlignOption != ""){
colStyle += 'style="text-align:'+option.column[i].columnTextAlignOption+'"';
}
html += '<div class="OY_UI_Column"' + colStyle + '>';
html += option.column[i].columnName;
html += '</div>';
}
html += '</div>'; // OY_UI_Rows
html += '</div>'; // OY_UI_Head
// row-data
html += '<div class="OY_UI_Body">';
let countKey = 0;
for(let i = 0; i < jsonData.length; i++){
html += '<div class="OY_UI_Rows">';
let keys = Object.keys(jsonData[i]);
// 무결성 data check
for(let k = 0; k < keys.length; k++){
let key = keys[k];
let jsonValue = jsonData[i][key];
let htmlValue = "";
// column data insert
for(let j = 0; j < option.column.length; j++){
let cnt = 0; // 첫 회 적용 여부 체크
if(option.column[j].keyId == key){
let styleEffect = '';
// column option =====
// activeOption
if(option.column[j].activeOption != null && option.column[j].activeOption != ""){
htmlValue += activeOptionCheck(option.column[j].activeOption, jsonValue);
}
// css
if(option.column[j].textAlignOption != null && option.column[j].textAlignOption != ""){
styleEffect += 'style="text-align:'+option.column[j].textAlignOption;
cnt = 1;
}
if(option.column[j].cellOption != null && option.column[j].cellOption != ""){
if(cnt == 1){
styleEffect += '; cursor: pointer;';
} else {
styleEffect += 'style="cursor: pointer;';
}
}
if(htmlValue == '' || htmlValue == null){
htmlValue += jsonValue;
}
if(styleEffect != "" && styleEffect != null){
styleEffect += '"';
}
html += '<div data-rowkey="'+countKey+'" data-index="'+i+'" class="OY_UI_Cell" '+styleEffect+'>'+htmlValue+'</div>';
countKey++;
}
htmlValue = '';
}
}
html += '</div>';
}
html += '</div>';
if(option.rowFootField != null && option.rowFootField != ""){
if(option.rowFootField == "rowFootField"){
html += '<div class="OY_UI_Foot footStyle">';
html += '<div class="OY_UI_Rows">';
for(let i = 0; i < option.column.length; i++){
html += '<div class="OY_UI_Cell">foot테스트</div>';
}
html += '</div>';
html += '</div>';
}
}
html += '</div>'; // OY_UI_Grid
htmlId.innerHTML = html;
},
insert: function(id, option, jsonData){
console.log("마지막 행 기준으로 추가 합니다.");
},
update: function(id, option, jsonData){
console.log("update !! ");
},
addActionEvent : function(id, event, callback){
let obj = document.getElementById(id);
// click event !!
if(event == "cellClick"){
return obj.addEventListener('click', (e) => callback(e));
}
}
};
Row Event 처리
Row별 값의 특정 입력 필드를 선택 하거나 값을 표현하게 할 수 있는 함수 생성
function activeOptionCheck(activeOption, jsonValue){
let htmlValue = '';
switch (activeOption){
case "inputField" :
// '<input type="text" value="'+jsonValue+'"/>'
htmlValue += '<div class="OY_UI_input">'+jsonValue+'</div>';
break;
case "dateField" :
htmlValue += ''+jsonValue;
break;
case "checkBox" :
htmlValue += '<div class="OY_UI_checkBox">';
if(jsonValue == 1){
htmlValue += '<input type="checkbox" class="OY_UI_checkBox check" checked/>';
} else {
htmlValue += '<input type="checkbox" class="OY_UI_checkBox check"/>';
}
htmlValue += '</div>';
break;
}
return htmlValue;
}
JsonArray Data를 이용한 Column, Grid 속성 추가
let option = {
column : [
{
columnName: "선택"
, keyId: "chk"
, activeOption: "checkBox"
},
{
columnName: "이름"
, keyId: "name"
, activeOption: "dateField"
, textAlignOption : "center"
, columnTextAlignOption : "center"
, cellOption : "pointer"
},
{
columnName: "입사날짜"
, keyId: "date"
, activeOption: "inputField"
, textAlignOption : "center"
, columnTextAlignOption : "center"
},
{
columnName: "직급"
, keyId: "rank"
, activeOption: "dateField"
, textAlignOption : "center"
, columnTextAlignOption : "center"
},
{
columnName: "연봉"
, keyId: "salary"
, activeOption: "dateField"
, textAlignOption : "left"
, columnTextAlignOption : "center"
}
] // column option
, width: "400"
, height: "100"
, eventAction : "functionName"
, rowFootField : "rowFootField"
, gridColorOption: ""
};
1번 컬럼 선택 checkBox 필드
2번 컬럼 이름 data viewer 필드
3번 컬럼 입사날짜 input 필드
4번 컬럼 직급 data viewer 필드
5번 컬럼 연봉 data viewer 필드
그리드 옵션 400px, 100px 사이즈 크기와 rowFootField 효과를 주었습니다.
Json 데이터
let jsonData = [
{ chk: 0
,name: "김삿갓"
,date: "2023-01-01"
,rank: "대리"
,salary: "4100"
},
{ chk: 0
,name: "황진이"
,date: "2023-02-01"
,rank: "과장"
,salary: "4700"
},
{
chk: 0
,name: "춘향이"
,date: "2023-03-01"
,rank: "대리"
,salary: "4200"
},
{
chk: 1
,name: "홍길동"
,date: "2023-04-01"
,rank: "차장"
,salary: "5500"
}
];
커스텀 이벤트 만들기
커스텀 이벤트 처리 (common.js의 addActionEvent() callBack function으로 커스텀 제어)
OYGrid.addActionEvent("myOYGrid", "cellClick", function(e){
let obj = e.target;
let eventJson = {
rowIndex : obj.dataset.index
, rowKey : obj.dataset.rowkey
, value : obj.innerHTML
};
if(eventJson.value == "김삿갓"){
let content = "";
content += "row Index : [" + eventJson.rowIndex;
content += "] row Key : [" + eventJson.rowKey;
content += "] row value : " + eventJson.value;
alert("누른 CELL => " + content);
}
});
value, key(무결성 체크용), index(gird 인덱스) 별로 조건을 넣어줄 수 있습니다.
대충 value로 조건을 걸어준다면.. 클릭한 Grid의 value가 김삿갓이라면
alert을 활성화 시킵니다.
결과


'Front-End > JavaScript' 카테고리의 다른 글
| JavaScript 공통 함수 정리(data to other data, dynamic events, Jquery-ajax) (0) | 2024.06.05 |
|---|---|
| Spring, Java, JavaScript (Jquery) Json, JsonList, File 한 번에 처리하는 방법(Multipart, Json, Ajax, formData) (0) | 2024.05.14 |