2013-01-04 5 views
0

나는 TD자바 스크립트 부착 클릭 이벤트 문제

내부 <a> 태그 설정에 click 이벤트를 시도하고 나는

test.prototype.buildData = function() { 
cell = createElement('td', {innerHTML: "<a class='link' onclick='"+this.edit(this)+"'>"+ value + "</a>"}); 
this.table.appendChild(cell); 

//many cells..all need to attached the click event 

} 

test.prototype.edit=function(this){ 
    this.style.backgroundColor='red' 
} 

내가 클릭 cellbackground color을 수정할 수 있습니다. 태그에만 click 이벤트를 등록해야합니다. 내 this.edit(this)은 이해가되지 않습니다.

어쨌든 이것을 할 수 있습니까? 고마워요!

+0

먼저 ... onclick을 사용하지 마십시오. – natlee75

답변

1

를 사용하여 그들 모두를 추적 할 수 있습니다 작성할 때 <a> -s에 ID를 할당 할 수

test.prototype.buildData = function (value) { 
    var cell = document.createElement("td"), 
     anchor = document.createElement("a"); 

    anchor.className = "link"; 
    anchor.addEventListener("click", (function (self) { 
     return function() { 
      self.edit(this); 
     }; 
    })(this), false); 
    anchor.innerHTML = value; 

    cell.appendChild(anchor); 

    this.table.appendChild(cell); 
}; 

test.prototype.edit = function (el) { 
    el.style.backgroundColor = "red"; 
}; 

NOTES :

  1. addEventListener 메서드를 통해 이벤트 처리기로 함수를 할당하면 함수 내의 this 값이 이벤트를 트리거 한 DOM 요소입니다.
  2. addEventListener의 두 번째 인수는 자바 스크립트의 모든 객체와 같은 단순한 객체 인 함수입니다. 따라서 실제 이벤트 처리 코드가 포함될 함수를 반환하는 즉시 호출 된 함수 식을 사용할 수 있습니다.
  3. JavaScript가 처음이라면 this의 값은 까다로울 수 있습니다. addEventListener 메서드의 "click"인수 바로 뒤에 괄호 안에 정의 된 함수 인 제 IIFE를 보면 false 인수 바로 앞에있는 인수로 this을 인수로 전달한다는 것을 알 수 있습니다.). 여기서 내가하는 일은 test.prototype과 같은 buildData 메서드의 관점에서 this의 값을 전달하는 것입니다. 그러나 IIFE는 self 인수로 간주하므로 반환 된 함수에서는 (즉 test.prototype) edit 메서드를 호출하며이 경우 인수를 this (이 경우 이벤트를 트리거 한 요소)이라고합니다.
  4. test.prototype.edit은 단일 인수로 요소를 가져와 배경색을 변경합니다.
1

자동 ... 당신이 그 (것)들을

var newCellId = 0; 
test.prototype.buildData = function() { 
    cell = createElement('td', 
    {innerHTML: "<a class='link' id='dynamicCellId_"+String(newCellId)+"'"+  value + "</a>"}); 
    this.table.appendChild(cell); 
    newCellId +=1; 
} 

그럼 당신은이 라인을 따라 뭔가를 시도 document.getElementById('dynamicCellId_X')

관련 문제