2013-07-24 17 views
1

我在网页上添加了HTML5按钮& DOM方法。我需要的是,当我点击一个特定的按钮时,相应的文本应该显示在alert中,相应的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> 

代码示例:http://jsfiddle.net/DerekL/9je7N/

回答

2

你的意思是你想alert名1如果单击第一submit

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 

更新:

要获得td元素感谢您的帮助内

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

第一个文本节点。现在工作正常。 – msg

+0

如果我在添加questiontext到列之前添加了新的按钮/ div组件,则此代码会给出空值。在这种情况下我必须做什么。 – msg

+0

此代码依赖于出现在'firstChild'位置的文本。请检查更新的小提琴。 –

相关问题