我试图通过使用输入按钮,从每一行的第一个td标签中获取文本,如下所示:
for(var i in obj.questions){
question += '<tr class="row">';
question += "<td>"+ obj.questions[i].question+"</td>";
question += '<td><input type="button" class="question" value="Add question" onclick="addQuestion()"></td>';
question += "</tr>";
document.getElementById("t01").innerHTML = question;
}
id=t01
用于表标记。这是我尝试过但不起作用的js:
var question;
$('.question').click(function() {
question = $(this).parent().find('td:first-child').text();
});
答案 0 :(得分:0)
您可能需要使用.live()
来实现此目的,具体取决于事件绑定和HTML生成的顺序。此外,考虑修改click
事件逻辑,以便遍历表的所有行以访问每个表行的“第一个单元格”文本:
// When the .question input is added to the DOM, this event logic will
// be bound to the input element automatically
$(document).live('.question', 'click', function() {
var question;
// Iterate over each row of the table
$('#t01 .row').forEach(function() {
// For each row, extract the text from first row cell
var row = $(this);
var firstCell = row.find('td:first-child');
var firstCellText = firstCell.text();
// Not sure how you want to use the data, this shows
// how to construct a comma separated string of text
// from all first row cells
question += firstCellText + ',';
});
// Print result to console
console.log(question);
});
答案 1 :(得分:0)
您必须像下面这样遍历每一行
$('.question').click(function () {
$('#t01 .row').each(function () {
console.log($(this).find("td:first-child").text());
});
});
我也建议使用jQuery而不是javascript而不是 document.getElementById(“ t01”)。innerHTML
$('#t01').html(question);
同样,您动态创建行的实现也有一个问题,您每次只会得到一行。您可以像下面那样更改代码
var question = "";
for (var i in questions) {
question += '<tr class="row">';
question += "<td>" + questions[i].question + "</td>";
question += '<td><input type="button" class="question" value="Add question" onclick="addQuestion()"></td>';
question += "</tr>";
}
$('#t01').html(question);
我为您创建了一个运行样本