들어가며
- 자바스크립트로 input 태그를 생성하고, input 태그에 이벤트를 발생하는 것이 현재의 목표다.
- 구체적인 시나리오는 input 태그를 최대 5개까지 생성할 수 있고, 태그를 동적으로 추가하거나 삭제할 수 있으며, 태그의 index는 유지된다. 각각의 값과 태그는 최대한 직관적으로 정리하였기에, 특별한 설명 없이 코드를 나열하겠다.
- 타입리프와 제이쿼리를 주로 사용했다.
코드뭉치
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function (){
var testForm = $("#testForm")
var index = 0
$("#insertButton").on("click", function (){
if(index == 5){
alert("5개 까지만 됩니다.")
return false;
}
var newDiv = document.createElement("div")
newDiv.setAttribute("class", "newDiv")
var newInput = document.createElement("input")
newInput.setAttribute("id", "newInput"+index)
newInput.setAttribute("id", "newInput"+index)
newInput.setAttribute("type", "text")
newInput.setAttribute("value", newInput.id)
var removeInput = document.createElement("span")
removeInput.setAttribute("class", "removeInput")
removeInput.textContent = "지우자"
newDiv.append(newInput)
newDiv.append(removeInput)
testForm.append(newDiv)
index+=1
$("#showIndex").text(index)
})
$(document).on("click", ".removeInput", function () {
$(this).parent(".newDiv").remove()
resetIndex()
})
function resetIndex(){
index = 0
testForm.children('div').each(function (){
var target = $(this).children(index, 'input[type=text]')
target.attr("id", "newInput"+index)
target.attr("value", target.attr("id"))
index+=1
})
$("#showIndex").text(index)
}
$("#readInputs").on("click", function () {
var result = ""
testForm.children('div').each(function (){
var target = $(this).children(index, 'input[type=text]')
result+=target.attr("id")+":"+target.val()+", "
})
alert(result)
})
$("#insertButton").trigger("click")
$("#insertButton").trigger("click")
$("#showIndex").text(index)
});
</script>
<div>
총 갯수 : <span id="showIndex"></span> / 5
</div>
<body>
<span id="insertButton" style="font-size: larger">복사하기</span>
<span id="readInputs" style="font-size: larger">읽기</span>
<form id="testForm">
</form>
</body>
</html>
자바스크립트와 DOM
- 자바스크립트를 사용함에 있어 항상 어려운 부분이 dom이다. dom 객체를 선정하고 조작하는 과정이 쉽지 않다. 특히 DOM의 경우 엔진과 렌더링 등에 대한 기반지식이 있어야 하는데 그것이 많이 부족한 상태이다.
- 현재로서 내가 이해한 단편적인 지식을 공유코자 한다. 현재의 코드뭉치 중 특별한 내용은 $(document) 와 $('selector').on('click', 'selector', function(){}...) 부분이다.
- dom은 한 번 생성 이후 더 이상 맵핑하지 않는다. 그러니까 뷰가 렌더링 한 이후 발생한 이벤트와 객체에 대하여 dom을 생성하지 못한다. 그러므로 dom을 다시 생성하기 위하여 $(document)를 사용한다.
- on은 bind, click 등 다양한 이벤트 객체를 대체하는 새로운 이벤트 코드이다. on을 권장하고 있다.