동적으로 생성한 엘리먼트에 이벤트 추가하기
1. attachEvent 메소드를 이용,
2. 동적으로 function 객체를 생성하여 할당
등이 있다. 첫번째 방법은 파라미터를 전달할 수 없으나, 두번째 방법은 파라미터를 마음대로 전달할 수 있다.
사용예는 아래를 참고바람.
<html> <head> <title></title> </head> <script type="text/javascript"> function OnClick1()
{ alert(event.srcElement.name); } function MyAlert(id, msg) { alert(id + " : " + msg); } function createButton() { var newRow = target.insertRow(); var newTd = newRow.insertCell(); var newInput = document.createElement("input"); newInput.setAttribute("type", "button"); newInput.setAttribute("value", "AttachEvent
Test"); newInput.attachEvent("onclick", OnClick1); newInput.name =
"First Input"; newTd.appendChild(newInput); newInput = document.createElement("input"); newInput.setAttribute("type", "button"); newInput.setAttribute("value", "Dynamic
Event Test"); newInput.name =
"Second Input"; newInput.onclick
= function() { MyAlert(newInput.name, "Possible
to pass many parameters dynamically!!"); } newTd.appendChild(newInput); } </script> <body> <input type="button"
value="New
Buttons" onclick="createButton()" /><p></p> <table id="target"> </table> </body> </html> |