Heim  >  Fragen und Antworten  >  Hauptteil

So rufen Sie Werte nicht ausgewählter Zeilen in einer HTML-Datentabelle mithilfe von JQuery ab

Ich versuche, den Wert aller Zeilen zu ermitteln, in denen nicht auf die Schaltfläche geklickt wird. Wenn ich beispielsweise in der ersten Zeile auf eine Schaltfläche klicke, möchte ich den Wert der Zeile abrufen, auf die nicht geklickt wurde.

 
var table = document.getElementById("all_department");
if (table != null) {
  for (var i = 0; i < table.rows.length; i++) {
  table.rows[i].onclick = function() {
  tableText(this);
      }
    }
  }    
    
function tableText(tableRow) {
var myJSON = JSON.stringify(tableRow);
console.log(myJSON);
}
    <table id="all_departments">
     <thead>
              <th><button>click</button></th>                                   
              <th>Departments</th>
              <th>Creation Date</th>
              <th>Name</th>
     </thead>
    <tbody class="bl">
           <tr>
                <td><button>click</button></td>
                <td>Management</td>
                <td>2-3-2016</td>
                <td>client x</td>
          </tr>
    
           <tr>
                <td><button>click</button></td>
                <td>Sales</td>
                <td>25-6-2019</td>
                <td>client y</td>
          </tr>
    </tbody>
    </table>

P粉431220279P粉431220279177 Tage vor1436

Antworte allen(1)Ich werde antworten

  • P粉561323975

    P粉5613239752024-04-06 00:50:27

    您可以监听按钮上的单击处理程序,获取单击按钮的父 tr,然后获取同级按钮。

    一旦获得所有兄弟姐妹,我们就可以循环它们并形成我们的结果字符串。

    请参考下面的代码

    const allBtns = document.querySelectorAll('button');
    allBtns.forEach(function(btn) {
      btn.addEventListener('click', function(e) {
        let elem = this.closest('tr');
        const siblings = getSiblings(elem);
        const result = [];
        siblings.map(ele => {
          ele.querySelectorAll('td').forEach((e, i) => {
            if (i !== 0) {
              result.push(e.innerText);
            }
          });
        });
        console.log(result.join(','));
      })
    });
    
    const getSiblings = function(e) {
      let siblings = [];
      if (!e.parentNode) {
        return siblings;
      }
    
      let sibling = e.parentNode.firstChild;
    
      while (sibling) {
        if (sibling.nodeType === 1 && sibling !== e) {
          siblings.push(sibling);
        }
        sibling = sibling.nextSibling;
      }
      return siblings;
    };
    Departments Creation Date Name
    Management 2-3-2016 client x
    Sales 25-6-2019 client y

    Antwort
    0
  • StornierenAntwort