首页 > 解决方案 > 获取与输入按钮在同一行中的第一个元素的值

问题描述

我正在尝试使用输入按钮从每行的第一个 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();                    
 });

标签: javascriptjqueryhtml

解决方案


您可能需要使用.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);
 });

推荐阅读