[英]how to get text in a row on clicking corresponding button?
我通過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>
代碼示例: http : //jsfiddle.net/DerekL/9je7N/
您是否要單擊第一個submit
來向Name1發出alert
?
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.