2013-01-10 1 views
2

이 (Firefox에서) 작동 ...자바 스크립트 동적으로하여 addEventListener와 노드 참조

window.onload = function() 
{ 
    CreateInputTable(); 
}; 

CreateInputTable = function() 
{ 
    var tbl = document.createElement('table'); 
    var tbo = document.createElement('tbody'); 
    var tr = document.createElement('tr'); 
    var td1 = document.createElement('td'); 
    var ib = document.createElement('input'); 
    ib.setAttribute('type', 'text'); 

    var tdID = "c1"; // Cell reference 

    if (ib.addEventListener)// all browsers except IE before version 9 - see http://help.dottoro.com/ljeuqqoq.php 
     { 
      ib.addEventListener('change', foo, false); 
     } 
    else// IE before version 9 - see http://help.dottoro.com/ljeuqqoq.php 
     { 
      ib.attachEvent('change', foo, false);  
     }; 

    td1.appendChild(ib); 
    tr.appendChild(td1); 

    var td2 = document.createElement('td'); 
    td2.setAttribute('id', tdID); 
    td2.appendChild(document.createTextNode("Hello world")); 
    tr.appendChild(td2); 

    tbo.appendChild(tr); 
    tbl.appendChild(tbo); 
    document.getElementsByTagName('body')[0].appendChild(tbl); 
}; 

function foo(){ 
    if (document.getElementById("c1")) 
     { 
     document.getElementById("c1").appendChild(document.createTextNode(" and goodbye"));    
     } 
}; 

그러나

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<script type="text/javascript" src="src/myJS.js"></script> 
</head> 
<body></body> 
</html> 

자바 스크립트 파일 (편의를 위해 전화 myJS.js), I 셀 참조 "c1"을 이벤트 리스너에 동적으로 전달하려고합니다. 내가 제대로 이해한다면, 나는 호출을 변경하지 못할

...

ib.addEventListener('change', foo(tdID), false); 

괄호가 foo의 반환 값, 함수로하지 foo를 반환하기 때문이다. foo이기 때문에

그러나, 나는 그것이 내가 제대로 이해한다면

function foo(){ 
    if (document.getElementById(tdID)) 
     { 
     document.getElementById(tdID).appendChild(document.createTextNode(" and goodbye"));    
     } 
}; 

this.var tdID = "c1"; 

... 그리고 foo는에 tdID의 선언을 변경하여 작업을 얻을 수 있습니다, 그것은 작동 CreateInputTable에서 호출되었으므로이 변수가 CreateInputTable에 있음을 알 수 있습니다.

그러나 tdID의 새 값으로 두 번째 행을 만들고 싶기 때문에 원하는 내용을 얻을 수 없습니다. 위의 예제는 단순히 셀 참조를 foo으로 하드 코딩하는 것 같습니다.

foo (객체 지향 스타일)에 셀 참조를 동적으로 전달할 수 있습니까?

+0

* (Object Oriented 스타일) * 코드 내에 "객체 지향적 인"것이 없습니다. –

답변

0

우아한 방법이 될 것이다 : foo(tdID9)에 대한 호출 인수의 오른쪽 숫자로 함수를 반환하고 있기 때문에

다음
function foo (tdID){ 
    return function(){ 
     if (document.getElementById(tdID)) 
     { 
      document.getElementById(tdID).appendChild(document.createTextNode(" and goodbye"));    
     } 
    } 
}; 

실제로

ib.addEventListener('change', foo(tdID), false); 

을 쓸 수 있습니다 "알고있다"는 내부 함수의 클로저에서 캡쳐되기 때문에`tdID '에 대한 올바른 값.

이 기술을 currying이라고합니다.

+0

감사합니다. – Extermiknit