【问题标题】:Table - Update cell on current row表格 - 更新当前行的单元格
【发布时间】:2021-12-15 09:56:00
【问题描述】:

我正在尝试使用 Select 中的值更新当前行的单元格 1。 我知道如果我用数字更改$(this).closest('tr'),它会影响该行,但不会触发当前行。

function currentrow(number) {
  document.getElementById('mytable').rows[$(this).closest('tr')].cells[1].innerHTML = number;
}
<table id="mytable">
  <tr>
    <td>
      <select name="column()" onchange="currentrow(this.value)">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3" selected>3</option>
      </select>
    </td>
    <td>
      3
    </td>
  </tr>
  <tr>
    <td>
      <select name="column()" onchange="currentrow(this.value)">
        <option value="1">1</option>
        <option value="2" selected>2</option>
        <option value="3">3</option>
      </select>
    </td>
    <td>
      2
    </td>
  </tr>
</table>

【问题讨论】:

  • 弄清楚。 ``` 函数 currentrow(select) { $(select).closest('tr').find("td:eq(1)").text(select.value) } ``

标签: html jquery html-table


【解决方案1】:

希望下面的回答对你有帮助

function currentrow(element) {
  element.parentNode.nextElementSibling.innerHTML = element.value;
}
<table id="mytable">
   <tr>
     <td>
       <select name="column()" onchange="currentrow(this)">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3" selected>3</option>
        </select>
     </td>
     <td>
       3
     </td>
   </tr>
  <tr>
     <td>
       <select name="column()" onchange="currentrow(this)">
          <option value="1">1</option>
          <option value="2" selected>2</option>
          <option value="3">3</option>
        </select>
     </td>
     <td>
       2
     </td>
   </tr>
</table>

详细视图

这里我把上面提到的JS代码拆分成多行。

function currentrow(element) {
  var selectedValue = element.value, // get selected value
    parentCell = element.parentNode, // get parent td element
    nextTargetCell = parentCell.nextElementSibling; // get next td element 
    
    // set next td element value with selected value 
    nextTargetCell.innerHTML = selectedValue; 
}
<table id="mytable">
   <tr>
     <td>
       <select name="column()" onchange="currentrow(this)">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3" selected>3</option>
        </select>
     </td>
     <td>
       3
     </td>
   </tr>
  <tr>
     <td>
       <select name="column()" onchange="currentrow(this)">
          <option value="1">1</option>
          <option value="2" selected>2</option>
          <option value="3">3</option>
        </select>
     </td>
     <td>
       2
     </td>
   </tr>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    相关资源
    最近更新 更多