无法读取属性“ childNodes”复选框以从同一行获取值

时间:2019-04-22 12:55:30

标签: javascript html

下面的代码应该为我提供表格中选中框旁边的列的值,但是,一旦单击按钮,我就会得到:

  

无法读取null的属性func Reads(i interface{}, column ColumnSpell) error { if err := DB.Debug().Find(i).Error; err != nil { return errors.New(fmt.Sprintf("Cannot reads %s: %s", column.Plural(), err.Error())) } return nil }

注意: firebase中的数据库,表中的值来自哪里

表格图片:

enter image description here

childNodes
rootRefReAgents.on("child_added", snap => {
  var AgentName = snap.child("Name").val();
  $("#table_body_Test").append("<tr><td>" + AgentName + "</td><td><INPUT TYPE=\"Checkbox\">  </Input></td></tr>");
});
}

function ActionData(){
  let agents = [];
  let table = document.getElementById("table_body_Test");
  let childNodes = Array.from(table.childNodes);
  // let childNodes = table.childNodes;
  for (let child of childNodes.values()) {
    console.log(`child: ${child}`);
    if (child.constructor.name !== "HTMLTableRowElement") {
        continue;
    }
    let agent = child.childNodes.item(1).innerHTML;
    console.log(`agent: ${agent}`);
    let checkbox = child.childNodes.item(3).childNodes.item(1);
    console.log(`checkbox: ${checkbox}`);
    console.log(checkbox.checked);
    if (checkbox.checked) {
        agents.push(agent);
    }
  }
  console.log(`agents: ${agents}`);
}

1 个答案:

答案 0 :(得分:1)

ES6带来了简化代码及其阅读的新方法

const tableBody = document.querySelector('#testTable tbody' );

document.querySelector('#submitBtn').onclick=()=>
{
  let agents = [];

  console.clear();
  
  for (let rowX of tableBody.rows )
  {
    let
      agent    = rowX.cells[0].textContent,
      checkbox = rowX.cells[1].querySelector('input[type=checkbox]')
    ;
    console.log( 'agent:', agent, 'checked:', checkbox.checked);

    if (checkbox.checked) { agents.push(agent); }
  }
  console.log( 'agents (array):', agents.join(' / '));
}
/// bonus info :
/*
rootRefReAgents.on("child_added", snap=>{
  let 
    newRow    = tableBody.insertRow(-1);

    newRow.insertCell(0).textContent = snap.child("Name").val();
    newRow.insertCell(1).innerHTML   = '<input type="Checkbox">';
});

*/
#testTable { margin: auto; border-collapse: collapse }
#testTable thead tr {
  color: #D2002E;
  background: #FFCC01;
  height:32px;
  font-weight: bold;
}
#testTable tr:nth-child(even) {background-color: lightgrey }
#testTable td { border:1px solid grey; padding: 0 20px; }
#testTable td:nth-child(2) { text-align: center }
<table id="testTable">
  <thead>
    <tr> <td>Agents</td> <td>Select</td> </tr>
  </thead>
  <tbody>
      <tr> <td>AMC</td>      <td> <input type="checkbox" >  </td> </tr>
      <tr> <td>Mygulfex</td> <td> <input type="checkbox" >  </td> </tr>
      <tr> <td>topStar</td>  <td> <input type="checkbox" >  </td> </tr>
      <tr> <td>WMC</td>      <td> <input type="checkbox" >  </td> </tr>
  </tbody>
</table>

<button id="submitBtn" >see Selects in console</button>

相关问题