簡體   English   中英

使用.each循環獲取元素屬性

[英]Get element attribute with .each loop

我有一個簡單的示例表,該表具有每個表行的數據屬性。

<table id="example">
  <tr data-sample="1">
    <th>Fox</th>
    <th>Sam</th>
    <th>Ted</th>
  </tr>
  <tr data-sample="2">
    <td>Bill</td>
    <td>Nick</td>
    <td>Pal</td>
  </tr>
  <tr data-sample="3">
    <td>El</td>
    <td>Pal</td>
    <td>Tea</td>
  </tr>
</table>

我正在嘗試使用以下代碼獲取所有data-sample屬性:

('#example tr').each(function () {
    console.log(this.data('sample'));
});

JS小提琴

我收到“ this.data不是函數”錯誤。 這使我意識到,在.each jquery循環中, this將返回DOM元素,而不是函數或任何我可以使用的選擇器(如果我僅打印出this ,則會得到表行及其子級的列表)。 有沒有什么辦法讓this作為一個選擇? ('#example').children('tr')('#example').find('tr')給出相同的結果。

jQuery語法錯誤

this不是jquery對象。使用$(this).data('sample')

 $('#example tr').each(function () { console.log($(this).data('sample')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> I have a simple example table that has data-attributes for every table row. <table id="example"> <tr data-sample="1"> <th>Fox</th> <th>Sam</th> <th>Ted</th> </tr> <tr data-sample="2"> <td>Bill</td> <td>Nick</td> <td>Pal</td> </tr> <tr data-sample="3"> <td>El</td> <td>Pal</td> <td>Tea</td> </tr> </table> 

或者使用attr()

  $('#example tr').each(function () {
        console.log($(this).attr('data-sample'));
    });

您的代碼中有兩個問題:

1)您需要將DOM對象轉換為jquery對象以與.data()

2)您在.data()中傳遞了錯誤的屬性參數。 應該是sample

$('#example tr').each(function () {
  console.log($(this).data('sample'));
});

有兩種方法可以做到這一點-

#1

$('#example tr').each(function () {
  console.log($(this).data('sample'));
});

#2

$('#example tr').each(function () {
  console.log($(this).attr('data-sample'));
});

檢查一下

$(document).ready(function(){
            $('#example tr').each(function () {             
                console.log($(this).attr("data-sample"));                   
            });
        });

如果要獲取行內容,請使用此

$('#example tr').each(function (i) { 
   alert($('#example tr[data-sample]')[i].innerText.split("\t"));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM