jQuery 在元素之前查找第一个属性
jQuery find the first attribut before an element
我有以下结构:
<tr data-commercial="commercial_8">
<td class="tdCommercial">
Mister X
<h4>Planning</h4>
<ul>
<li data-day="Monday">
<i class="fa fa-plus-square fa-1"></i>
<i class="fa fa-minus-square fa-1"></i>
Lundi
<span class="number">2</span>
</li>
<li data-day="Tuesday">
<li data-day="Wednesday">
<li data-day="Thursday">
<li data-day="Friday">
</ul>
</td>
<td class="Monday"></td>
<td class="Tuesday"></td>
<td class="Wednesday"></td>
<td class="Thursday"></td>
<td class="Friday"></td>
<td class="Saturday"></td>
<td class="Sunday"></td>
</tr>
对于jQuery,我正在使用带有元素<i class="fa fa-plus-square fa-1"></i>
的onClick
事件。
从此元素中检索第一个tr
的 data-commercial
属性的最佳方法是什么?
结构可以改变,所以我需要类似"在myElement
之前找到第一个数据商业属性"
谢谢!
使用 .closest()
对于集合中的每个元素,通过测试元素本身并在 DOM 树中遍历其祖先来获取与选择器匹配的第一个元素。
例:
var commercial = $(this).closest('tr').data('commercial');
注意:前提是this
是指元素<i class="fa fa-plus-square fa-1"></i>
$('#myElement').closest('tr').attr('data-commercial');
使用最接近:
$(this).closest('tr').data('commercial');
$(this).parents("tr").data("commercial")
在 jquery 中使用 .closest()
$(this).closeset('tr').data('commercial');
相关文章:
- 而循环只设置php中输入字段中的第一个值
- 错误:$injector:modulerr模块错误(我的第一个SPA应用程序)
- IE11中的第二个调用取消了第一个Fetch API调用
- Javascript XMLHttpRequest——只有第一个POST请求有效
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- RxJS油门行为;立即获取第一个值
- Angular UI网格:如何通过第一个UI网格中的按钮使第二个UI网格可见
- 选择多个实例中的第一个
- 如何在调用下一个请求之前完成第一个Ajax Get请求
- Lodash:返回对象的第一个键,该对象的值(即数组)中有一个给定的元素(即字符串)
- 在对象中查找下一个键id
- 看起来第一个console.log是'It’不太对
- 查找上一个<p>在第n个字符之后
- 使用jQuery只查找第一个类
- 在JavaScript中查找数字对列表的最小第一个值
- 仅在第一个li内查找h2
- 如何编写一个选择器来查找第一个“输入”.在类为“x”的元素之后
- 使用jQuery查找任何后代的第一个id
- 使用脚本查找文本字符串,直到第一个html标记