2013-07-24 2 views
1

웹 페이지에서 DOM 메소드 인 HTML5 버튼 & 텍스트를 추가했습니다. 내가 필요한 것은 특정 버튼을 클릭했을 때 해당 Btn_ID & 해당 텍스트가 경고에 표시되어야한다는 것입니다. 해당 Btn_ID가 표시되지만 텍스트를 가져올 수 없습니다.해당 버튼을 클릭하면 텍스트를 연속으로 가져 오는 방법은 무엇입니까?

내 코드는;

<head> 
    <style> 
    .tbls { 
     height:60px; 
     width:100%; 
    } 
    .Rows { 
     height:60px; 
     width:100%; 
     background-color:lightblue; 
    } 
    .Btn { 
     height:40px; 
     width:70px; 
    } 
    </style> 
</head> 

<body> 
    <div id='contnt'></div> 
</body> 
<script> 
var arry = ["Name 1", "Name 2", "Name 3", "Name 4", "Name 5"]; 
var container = document.getElementById('contnt'); 
for(var j = 0; j < arry.length; j++) { 
    var tbls = document.createElement('table'); 
    tbls.className = 'tbls'; 
    var Rows = document.createElement('tr'); 
    Rows.className = 'Rows'; 
    var Column = document.createElement('td'); 
    var questionlist = document.createTextNode(arry[j]); 
    Column.appendChild(questionlist); 
    var Btn = document.createElement('button'); 
    Btn.id = j; 
    Btn.className = 'Btn'; 
    Btn.innerHTML = 'SUBMIT'; 
    Btn.onclick = function() { 
     alert(this.id); 
     alert(this.parentElement.questionlist); 
    } 
    Column.appendChild(Btn); 
    Rows.appendChild(Column); 
    tbls.appendChild(Rows); 
    container.appendChild(tbls); 
} 
</script> 

코드 예제 :

답변

2

http://jsfiddle.net/DerekL/9je7N/ 처음 submit가 클릭하면 당신이 alert 이름 1 원하는 의미합니까?

Btn.onclick = function() { 
    alert(this.id); 
    alert(this.parentElement.firstChild.nodeValue); 
} 

//this.parentElement = Your table cell 
//this.parentElement.firstChild = text node (questionlist) 
//this.parentElement.firstChild.nodeValue = text node's value //Name1, Name2 

업데이트 :

이 도움을 주셔서 감사합니다

Btn.onclick = function() { 
    alert(this.id); 
    var children = this.parentElement.childNodes; 
    var text; 
    for(var i = 0; i < children.length; i ++) { 
     if(children[i].nodeType === Node.TEXT_NODE) { 
      text = children[i].nodeValue; 
      break; 
     } 
    } 
    alert(text); 
} 

jsFiddle Demo

Updated jsFiddle Demo

+0

td 요소 내에 첫 번째 텍스트 노드를 얻을 수 있습니다. 지금은 괜찮아. – msg

+0

질문지를 열에 추가하기 전에 새로운 button/div 구성 요소를 추가하면이 코드는 null 값을 제공합니다. 이 사건에서 내가해야 할 일. – msg

+0

이 코드는 'firstChild' 위치에있는 텍스트에 의존합니다. 업데이트 된 바이올린을 확인하십시오. –

관련 문제