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/
第一个文本节点。现在工作正常。 – msg
如果我在添加questiontext到列之前添加了新的按钮/ div组件,则此代码会给出空值。在这种情况下我必须做什么。 – msg
此代码依赖于出现在'firstChild'位置的文本。请检查更新的小提琴。 –