javascript - 获取与输入按钮在同一行中的第一个元素的值
问题描述
我正在尝试使用输入按钮从每行的第一个 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();
});
解决方案
您可能需要使用.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);
});
推荐阅读
- kubernetes - Prometheus 使用多个目标
- git - 如何在 Jenkins 上添加 dockerhub 凭据?
- java - HashMap 行为怪异
- php - 如果 php 和 jQuery 选中或未选中,则在 php 中动态创建复选框值
- html - 当我打印带有背景图像的 HTML 页面时,没有显示文本
- javascript - D3.js 在决策树中绘制菱形和连接链接
- javascript - 将javascript函数输出分配给液体变量
- image - 第一次打开或清除所有数据时,React Native 应用程序加载 url 图像很慢
- python - 使用 spacy 自定义标记器时 ReversibleField 失败
- python - 我尝试使用 pip 安装 win32gui,但出现此错误。我正在使用 python 3.8.5,我也有最新版本的 pip