我有这样设置的表:

<table id="mantab" style="cursor:pointer;" onkeypress="scan(event)">
<tr>
  <a href="#" data-popover=".popover-help" class="open-popover modal-in"></a>
  <td><input type='text' placeholder="Term" id='inp1' class="inp1" /></td>
  <td><input type='text' placeholder="Definition" id='inp2' class="inp2" /></td>
</tr>
</table>


可以采取行动在此表中添加一行,这是通过insertCell方法插入一个单元格并适当设置该单元格的innerHTML来完成的。

我一直在尝试遍历表的第一列,并将每个单元格中的输入值(输入后)加起来,并以逗号分隔字符串。第二列应重复此过程。

问题:


我尝试阅读的所有内容均未定义

我尝试了以下方法来检索单元格的内容:

document.getElementById(“ id”)。value,

document.getElementByClassName(“ classname”)。value,

table.rows [0] .cells [0] .value,

table.rows [0] .cells [0] .val(),

table.rows [0] .cells [0] .innerHTML,

table.rows [0] .cells [0] .children [0] .val()


没有任何效果,有些返回空白,大多数未定义。 innerHTML会返回单元格内部的input元素,但是没有实际的文本输入数据。

如果需要更清楚地了解我在看什么,请参阅以下内容:

javascript - 从HTML表格中的输入元素中检索值-LMLPHP

这应该返回一个包含字符串的变量:“ KeyA,KeyB,KeyC”,另一个包含:“ ValueA,ValueB,ValueC”

我对javascript有点陌生,但是我对其他几种语言有基本的了解。我不确定为什么要遍历表会带来如此大的挑战。任何有助于阐明如何提取这些“不可见”值的帮助将不胜感激。谢谢。

这是对我不起作用的许多方法之一:

for (var i = 0, row; row = table.rows[i]; i++) {
   for (var j = 0, col; col = row.cells[j]; j++) {
       if(j == 0) { //if first column
            words += col.getElementsByClassName("inp1").value + ","; //inp1 refers to first column input class name
       } else {
            defs += col.getElementsByClassName("inp2").value + ","; //inp2 refers to second column input class name
      }
   }
}


在此示例中,单词与上图中的第一个变量相似,而defs到第二个变量。

更新:记录值和负责提供值的元素导致:

javascript - 从HTML表格中的输入元素中检索值-LMLPHP

第一个日志为空,第二个日志未分配值,即使我键入了一些内容也是如此。

最佳答案

您可以使用jQuery选择器执行类似的操作



$("#bt").click(function()
{
  var keys = [], values = [];

  $('table tr input').each(function(i,e){
  //access the input's value like this:
    var $e = $(e);
    if($e.hasClass('key')){
    	keys.push($e.val());
    }else{
    values.push($e.val());
    }
});
  keys = keys.join(',');
  values = values.join(',');
  console.log(keys);
  console.log(values);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mantab" style="cursor:pointer;">
<tr>
  <a href="#" data-popover=".popover-help" class="open-popover modal-in"></a>
  <td><input type='text' placeholder="Term" id='inp1' class="key" /></td>
  <td><input type='text' placeholder="Definition" id='inp2' class="value" /></td>
</tr>
<tr>
  <a href="#" data-popover=".popover-help" class="open-popover modal-in"></a>
  <td><input type='text' placeholder="Term" id='inp1' class="key" /></td>
  <td><input type='text' placeholder="Definition" id='inp2' class="value" /></td>
</tr>
</table>

<button id="bt">
Get Value
</button>

关于javascript - 从HTML表格中的输入元素中检索值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39188992/

10-12 13:01
查看更多