[英]jQuery parent or parents to get data-attribute in table th tag
I have a table that are like a grid with a horizontal list in the top with week numbers within th
tags and below each week are different values in rows of tr
and td
tags. 我有一张表格,它像一个网格,顶部有一个水平列表,在
th
标签内有周数,在每个周下面的tr
和td
标签行中有不同的值。
I'm trying to get the data-attribute
for the week
when I click below in one of the td
tags with the data-id attribute
. 我试图让
data-attribute
的week
,当我在一个点击以下td
与标签data-id attribute
。 But I can't get it right and wonder what I have done wrong to be able to read this value? 但是我无法正确理解并想知道我做错了什么才能读取此值?
Some of the combinations I have tested: 我测试过的一些组合:
var test = $(this).closest("th").attr("data-week");
var test = $(this).parents().find(".week").attr("data-week");
var test = $(this).parents("th").attr("data-week");
The HTML with data-attributes for the table: 带有数据属性的HTML表格:
<table>
<thead>
<tr>
<th class=""></th>
<th class="week" data-week="15">15</th>
<th class="week" data-week="16">16</th>
<th class="week" data-week="17">17</th>
<th class="week" data-week="18">18</th>
<th class="week" data-week="19">19</th>
</tr>
</thead>
<tbody>
<tr>
<td>Stina (1)</td>
<td data-id="40">10</td>
<td data-id="12">20</td>
<td data-id="13">40</td>
<td data-id="14">45</td>
<td data-id="15">40</td>
</tr>
<tr>
<td>Linda (2)</td>
<td data-id="0">0</td>
<td data-id="0">0</td>
</tr>
<tr>
<td>Lasse (3)</td>
<td data-id="21">5</td>
<td data-id="22">39</td>
<td data-id="23">40</td>
<td data-id="24">40</td>
</tr>
</tbody>
</table>
@Sean DiSanti, good one! @Sean DiSanti,好人! Here is a slightly more efficient version, without warping $ in $, by using eq method
这是一个效率更高的版本,使用eq方法不会使$ in $变形
$('td').on('click', function(e) {
var index = $(this).index() -1;
var week = $('.week').eq(index).data('week');
console.log('week', week);
});
Here is a way you can find the data-week attribute of the clicked th element. 您可以通过以下方式找到被点击的元素的数据周属性。
$(document).ready(function(){
$("td").on("click",function(){
$td=$(this);
$th = $td.closest('table').find('th').eq($td.index());
alert($th.attr("data-week"));
});
});
Demo : https://jsfiddle.net/7b146hor/2/ 演示 : https : //jsfiddle.net/7b146hor/2/
You need to find it by index. 您需要按索引找到它。 Get which child number the clicked element has and then look for same number in
.weeks
获取被单击元素具有的子编号,然后在
.weeks
查找相同的编号
$('td').on('click', function(e){
index = $(this).index();
week = $('.weeks').find(":eq("+index+")").attr('data-week');
console.log(week);
});
This worked for me 这对我有用
$('td').on('click', function(e) {
index = $(this).index();
week = $($('.week')[index - 1]).data('week');
console.log('week', week);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.