[英]Getting attribute of a parent node
我正在尝试使用
$(this).parentNode.attr('data-element')
它应该在字符串中返回0 - 5但它不起作用。 我在这样的函数中使用它
$('.someClass').each(function(){
$(this).html(SomeFunction('SomeString', $(this).parentNode.attr('data-element')));
});
类'someClass'的所有元素都有一个parentNode
<li class="element" data-element: 1 (or any number from 0 to 5 (including))> </li>
而且我不知道错误在哪里。 我究竟做错了什么?
- 大卫
你在同一行代码中混合jQuery和普通javascript,这是行不通的。 你可以使用:
$(this).parent().attr('data-element'); // jQuery
要么
this.parentNode.getAttribute("data-element"); // plain javascript
parentNode
不是jQuery对象的属性,所以你不能像你那样混合它们。 获取父级的jQuery方法是.parent()
。
你应该做
$(this).parent().attr('data-element')
因为你不能在非jQuery对象上调用attr()
尝试这样做:
$(this).parent().attr('data-element');
有关.parent()等函数的更多信息,请参阅JQuery文档的遍历部分: http ://api.jquery.com/category/traversing/
使用jquery应该是:
$(this).parent().attr('data-element');
不使用jquery,这将是:
this.parentNode.getAttribute("data-element")
我更喜欢使用:
var item = $(this);
var parent = item.closest(".element"); //using the class for selection
//and then use parent.attr('data-element')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.