1. 윈도우 요소를 다 적재한 이후의 방식
<script>
window.onload = function(){
var box = document.getElementById('box');
box.onclick = function(){
alert('이벤트 등록');
}
};
</script>
<div id="box">클릭</div>
window.onload
document.getElementById('box');
box.onclick
2. 함수를 먼저 제작화는 방식
<script>
function addElem(){
var btn=document.getElementById('btn');
function func(){
var div = document.createElement('div')
document.body.appendChild(div);
}
btn.onclick = func;
}
addEventListener('load', addElem);
</script>
<button id="btn">버튼을 누르면 요소를 생성합니다.</button>
var div = document.createElement('div')
document.body.appendChild(div);
btn.onclick = func;
addEventListener('load', addElem)
- 페이지 전체가 로드 되었을 때 addElem 함수 기동
링크 심기
<script>
function addElem(){
var btn=document.getElementById('btn');
function func(){
var div=document.createElement('div');
var a=document.createElement('a');
var txt=document.createTextNode('링크');
a.appendChild(txt);
a.setAttribute('href','https://www.naver.com/');
div.appendChild(a);
document.body.appendChild(div);
}
btn.onclick = func;
}
addEventListener('load',addElem);
</script>
<button id="btn">버튼을 누르면 요소를 생성합니다.</button>
var div=document.createElement('div');
var a=document.createElement('a');
var txt=document.createTextNode('링크');
a.appendChild(txt);
a.setAttribute('href','https://www.naver.com/');
div.appendChild(a);
document.body.appendChild(div);