获取父节点的属性
我正在尝试使用
$(this).parentNode.attr('data-element')
which 应该在字符串中返回 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>
,我不知道错误在哪里。我做错了什么?
——大卫
I am trying to use
$(this).parentNode.attr('data-element')
which should return 0 - 5 in string but it just won't work. I am using it in a function like this
$('.someClass').each(function(){
$(this).html(SomeFunction('SomeString', $(this).parentNode.attr('data-element')));
});
All the elements with class 'someClass' have a parentNode
<li class="element" data-element: 1 (or any number from 0 to 5 (including))> </li>
and I have no idea where is the mistake. What am I doing wrong?
--David
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您在同一行代码中混合了 jQuery 和纯 JavaScript,这是行不通的。您可以使用:
或
parentNode
不是 jQuery 对象的属性,因此您不能按照您的方式混合使用这两者。获取父级的 jQuery 方法是.parent()
。You are mixing jQuery and plain javascript in the same line of code and that will not work. You can either use:
or
parentNode
is not a property of a jQuery object, so you can't mix the two the way you were doing it. The jQuery method for getting the parent is.parent()
.你应该这样做
,因为你不能在非 jQuery 对象上调用
attr()
You should do
because you can't call
attr()
on a non jQuery object尝试这样做:
有关 .parent() 等函数的更多信息,请参阅 JQuery 文档的遍历部分:
http://api.jquery.com/category/traversing/
Try doing this instead:
For more information on functions like .parent() see the Traversing section of the JQuery documentation:
http://api.jquery.com/category/traversing/
使用 jquery 应该是:
不使用 jquery 这将是:
Using jquery it should be:
Without using jquery this would be:
我更喜欢使用:
I prefer to use: