Pobierz zawartość wiersza tabeli za pomocą kliknięcia przycisku

Muszę wyodrębnić szczegóły każdej kolumny w tabeli. Na przykład kolumna " Nazwa / Nr.".

  • tabela zawiera kilka adresów
  • ostatnia kolumna każdego wiersza ma przycisk, który pozwala użytkownikowi wybrać podany adres.

Problem: Mój kod pobiera tylko pierwszą <td>, która ma klasę nr. Jak to uruchomić?

Oto bit jQuery:

$(".use-address").click(function() {
    var id = $("#choose-address-table").find(".nr:first").text();
    $("#resultas").append(id); // Testing: append the contents of the td to a div
});

Tabela:

<table id="choose-address-table" class="ui-widget ui-widget-content">
    <thead>
        <tr class="ui-widget-header ">
            <th>Name/Nr.</th>
            <th>Street</th>
            <th>Town</th>
            <th>Postcode</th>
            <th>Country</th>
            <th>Options</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="nr"><span>50</span>
            </td>
            <td>Some Street 1</td>
            <td>Leeds</td>
            <td>L0 0XX</td>
            <td>United Kingdom</td>
            <td>
                <button type="button" class="use-address" />
            </td>
        </tr>
        <tr>
            <td class="nr">49</td>
            <td>Some Street 2</td>
            <td>Lancaster</td>
            <td>L0 0XX</td>
            <td>United Kingdom</td>
            <td>
                <button type="button" class="use-address" />
            </td>
        </tr>
    </tbody>
</table>
Author: Brian Tompsett - 汤莱恩, 2013-01-22

8 answers

Celem ćwiczenia jest znalezienie wiersza zawierającego informacje. Kiedy tam dotrzemy, możemy łatwo wyodrębnić wymagane informacje.

Odpowiedź

$(".use-address").click(function() {
    var $item = $(this).closest("tr")   // Finds the closest row <tr> 
                       .find(".nr")     // Gets a descendent with class="nr"
                       .text();         // Retrieves the text within <td>

    $("#resultas").append($item);       // Outputs the answer
});

ZOBACZ DEMO

Teraz skupmy się na najczęściej zadawanych pytaniach w takich sytuacjach.

Jak znaleźć najbliższy rząd?

Za pomocą .closest():

var $row = $(this).closest("tr");

Za pomocą .parent():

Możesz także poruszać się po drzewie DOM za pomocą .parent() metoda. Jest to tylko alternatywa, która jest czasami używana razem z .prev() i .next().

var $row = $(this).parent()             // Moves up from <button> to <td>
                  .parent();            // Moves up from <td> to <tr>

Pobieranie wszystkich komórek tabeli <td> wartości

Mamy więc nasz $row i chcielibyśmy wypisać tekst komórki tabeli:

var $row = $(this).closest("tr"),       // Finds the closest row <tr> 
    $tds = $row.find("td");             // Finds all children <td> elements

$.each($tds, function() {               // Visits every single <td> element
    console.log($(this).text());        // Prints out the text within the <td>
});

ZOBACZ DEMO

Uzyskanie określonej <td> wartości

Podobny do poprzedniego, jednak możemy określić indeks elementu potomnego <td>.

var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element

$.each($tds, function() {                // Visits every single <td> element
    console.log($(this).text());         // Prints out the text within the <td>
});

Widok DEMO

Przydatne metody

  • .closest() - Pobierz pierwszy element pasujący do selektora
  • .parent() - jest to Element nadrzędny dla każdego elementu w bieżącym zestawie dopasowanych elementów.]}
  • .parents() - w tym celu należy pobrać wszystkie elementy z aktualnego zbioru dopasowanych elementów.]}
  • .children() - w zależności od tego, czy jest to element, czy Element, czy Element, czy Element.]}
  • .siblings() - get the rodzeństwo każdego elementu w zbiorze dopasowanych elementów
  • .find() - pobieramy Potomków każdego elementu w bieżącym zestawie dopasowanych elementów
  • .next() - aby uzyskać natychmiastowe potomstwo każdego elementu w zbiorze dopasowanych elementów
  • .prev() - w zależności od tego, czy dany element jest dopasowany do danego elementu, czy też nie, każdy element musi być dopasowany do danego elementu.]}
 184
Author: martynas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-11 10:05:16

Spróbuj tego:

$(".use-address").click(function() {
   $(this).closest('tr').find('td').each(function() {
        var textval = $(this).text(); // this will be the text of each <td>
   });
});

To znajdzie najbliższy tr (przechodzący w górę Przez DOM) aktualnie klikniętego przycisku, a następnie zapętli każdy td - możesz chcieć utworzyć łańcuch / tablicę z wartościami.

Przykład tutaj

Uzyskanie pełnego adresu za pomocą przykładu tablicy tutaj

 8
Author: ManseUK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-22 14:18:12

Musisz zmienić kod, aby znaleźć wiersz względem przycisku, który został kliknięty. Spróbuj tego:

$(".use-address").click(function() {
    var id = $(this).closest("tr").find(".nr").text();
    $("#resultas").append(id);
});

Przykładowe skrzypce

 7
Author: Rory McCrossan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-22 14:09:23

Selektor ".nr:first" szuka w szczególności pierwszego i tylko pierwszego elementu posiadającego klasę "nr" wewnątrz wybranego elementu tabeli. Jeśli zamiast tego wywołasz .find(".nr"), otrzymasz wszystkie elementy w tabeli posiadające klasę "nr". Gdy już masz wszystkie te elementy, możesz użyć .każda metoda iteracji nad nimi. Na przykład:

$(".use-address").click(function() {
    $("#choose-address-table").find(".nr").each(function(i, nrElt) {
        var id = nrElt.text();
        $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
    });
});

Jednakże, otrzymałbyś wszystkie z td.nr elementów w tabeli, a nie tylko ten w wierszu, który był / align = "left" / Aby ograniczyć wybór do wiersza zawierającego kliknięty przycisk, Użyj .najbliższa metoda , jak tak:

$(".use-address").click(function() {
    $(this).closest("tr").find(".nr").each(function(i, nrElt) {
        var id = nrElt.text();
        $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
    });
});
 1
Author: dgvid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-22 14:14:07
function useAdress () { 
var id = $("#choose-address-table").find(".nr:first").text();
alert (id);
$("#resultas").append(id); // Testing: append the contents of the td to a div
};

Następnie na przycisku:

onclick="useAdress()"
 1
Author: cody collicott,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-06 09:37:29

Znajdź element o id w wierszu używając jquery

$(document).ready(function () {
$("button").click(function() {
    //find content of different elements inside a row.
    var nameTxt = $(this).closest('tr').find('.name').text();
    var emailTxt = $(this).closest('tr').find('.email').text();
    //assign above variables text1,text2 values to other elements.
    $("#name").val( nameTxt );
    $("#email").val( emailTxt );
    });
});
 0
Author: Super Model,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-10 11:00:59
var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
   $(this).find("td").each(function () {
       values[count] = $(this).text();
       count++;
    });
});

Teraz tablica wartości zawiera wszystkie wartości komórek tego wiersza może być używany jak wartości[0] pierwsza wartość komórki klikniętego wiersza

 0
Author: Muhammad Waqas Aziz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-28 07:15:41

Oto kompletny kod dla prostego przykładu delegata

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">
  <h2>Striped Rows</h2>
  <p>The .table-striped class adds zebra-stripes to a table:</p>            
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>

      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>

    </tbody>
  </table>
  <script>
  $(document).ready(function(){
  $("div").delegate("table tbody tr td:nth-child(4)", "click", function(){
  var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)");
     $.each($tds, function() {
        console.log($(this).text());
        var x = $(this).text();
        alert(x);
    });
    });
});
  </script>
</div>

</body>
</html>
 0
Author: ankush,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-16 18:48:31