我添加了HTML5按钮&网页中的文字'DOM方法。我需要的是,当我点击一个特定的按钮时,它是相应的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>
答案 0 :(得分:2)
如果点击第一个alert
,您是否想要submit
Name1?
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);
}