从HTML

时间:2016-08-28 07:33:56

标签: javascript html input html-table cell

我有一个表格设置如下:

<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]。儿童[0] .VAL()

无效,有些返回空白,大多数未定义。 innerHTML返回单元格内的输入元素,但没有实际的文本输入数据。

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

enter image description here

这应返回一个包含字符串的变量:“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指向第二个变量。

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

enter image description here

第一个日志为空白,第二个日志没有分配值,即使我输入了某些内容。

2 个答案:

答案 0 :(得分:1)

您可以使用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>

答案 1 :(得分:0)

如何使用jQuery并查找表中的所有输入:

$('table input').each(function(i,e){
  //access the input's value like this:
  console.log($(e).val());
});