我正在尝试使用
$(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()
。
关于javascript - 获取父节点的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9126264/