버튼 클릭으로 테이블 행의 내용 가져 오기
테이블의 각 열에 대한 세부 정보를 추출해야합니다. 예를 들어, "Name / Nr."열.
- 테이블에는 여러 주소가 포함되어 있습니다.
- 각 행의 맨 마지막 열에는 사용자가 나열된 주소를 선택할 수있는 버튼이 있습니다.
문제 : 내 코드 <td>
는 클래스가있는 첫 번째 코드 만 선택합니다 nr
. 이 작업을 수행하려면 어떻게해야합니까?
다음은 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
});
표:
<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>
연습의 목적은 정보가 포함 된 행을 찾는 것입니다. 거기에 도착하면 필요한 정보를 쉽게 추출 할 수 있습니다.
대답
$(".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
});
이제 이러한 상황에서 자주 묻는 질문에 집중 해 보겠습니다.
가장 가까운 행을 찾는 방법?
사용 .closest()
:
var $row = $(this).closest("tr");
사용 .parent()
:
.parent()
메서드를 사용하여 DOM 트리를 위로 이동할 수도 있습니다 . 이것은 때때로와 함께 사용되는 단지 대안 .prev()
과 .next()
.
var $row = $(this).parent() // Moves up from <button> to <td>
.parent(); // Moves up from <td> to <tr>
모든 테이블 셀 <td>
값 가져 오기
그래서 우리는 $row
표 셀 텍스트를 출력하고 싶습니다.
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>
});
특정 <td>
가치 얻기
이전 항목과 유사하지만 하위 <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>
});
유용한 방법
.closest()
-선택자와 일치하는 첫 번째 요소를 가져옵니다..parent()
-현재 일치하는 요소 집합에서 각 요소의 부모를 가져옵니다..parents()
-현재 일치하는 요소 집합에서 각 요소의 조상을 가져옵니다..children()
-일치하는 요소 집합에서 각 요소의 자식을 가져옵니다..siblings()
-일치하는 요소 집합에서 각 요소의 형제를 가져옵니다..find()
-현재 일치하는 요소 집합에서 각 요소의 하위 항목을 가져옵니다..next()
-일치하는 요소 집합에서 각 요소의 바로 다음 형제를 가져옵니다..prev()
-일치하는 요소 집합에서 각 요소의 바로 앞 형제를 가져옵니다.
클릭 한 버튼과 관련된 행을 찾으려면 코드를 변경해야합니다. 이 시도:
$(".use-address").click(function() {
var id = $(this).closest("tr").find(".nr").text();
$("#resultas").append(id);
});
이 시도:
$(".use-address").click(function() {
$(this).closest('tr').find('td').each(function() {
var textval = $(this).text(); // this will be the text of each <td>
});
});
이것은 tr
현재 클릭 된 버튼 에서 가장 가까운 (DOM을 통해 올라가는)를 찾은 다음 각각을 반복 td
합니다. 값으로 문자열 / 배열을 생성 할 수 있습니다.
선택기 ".nr:first"
는 "nr"
선택한 테이블 요소 내에서 클래스를 갖는 첫 번째 요소 만 찾습니다 . 대신 호출 .find(".nr")
하면 class가있는 테이블 내의 모든 요소를 얻을 수 "nr"
있습니다. 이러한 요소가 모두 있으면 .each 메서드를 사용하여 반복 할 수 있습니다. 예를 들면 :
$(".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
});
});
그러나 클릭 한 행 의 요소뿐만 아니라 테이블 의 모든td.nr
요소를 가져옵니다 . 클릭 한 버튼이 포함 된 행으로 선택을 제한하려면 다음 과 같이 .closest 메서드를 사용합니다 .
$(".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
});
});
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
};
그런 다음 버튼 :
onclick="useAdress()"
jquery를 사용하여 행에서 ID가있는 요소 찾기
$(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 );
});
});
var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
$(this).find("td").each(function () {
values[count] = $(this).text();
count++;
});
});
이제 값 배열에 해당 행의 모든 셀 값이 포함되어 클릭 된 행의 값 [0] 첫 번째 셀 값처럼 사용할 수 있습니다.
Here is the complete code for simple example of delegate
<!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>john@example.com</td>
<td>click</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@example.com</td>
<td>click</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@example.com</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>
참고URL : https://stackoverflow.com/questions/14460421/get-the-contents-of-a-table-row-with-a-button-click
'IT TIP' 카테고리의 다른 글
Keras의 HDF5 파일에서 모델을로드하는 방법은 무엇입니까? (0) | 2020.11.02 |
---|---|
프로그래밍 방식으로 UITextField의 모든 텍스트 선택 (0) | 2020.11.02 |
Android Studio에서 AVD 에뮬레이터 창의 크기를 조정하는 방법은 무엇입니까? (0) | 2020.11.02 |
시작할 때 시작할 프로그램을 어떻게 설정합니까? (0) | 2020.11.02 |
다음 두 줄의 실행 사이에 지연 추가 (0) | 2020.11.02 |