Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取父节点的属性_Javascript_Jquery_Html_Parent - Fatal编程技术网

Javascript 获取父节点的属性

Javascript 获取父节点的属性,javascript,jquery,html,parent,Javascript,Jquery,Html,Parent,我正在尝试使用 $(this).parentNode.attr('data-element') 它应该在字符串中返回0-5,但它就是不起作用。我在这样的函数中使用它 $('.someClass').each(function(){ $(this).html(SomeFunction('SomeString', $(this).parentNode.attr('data-element'))); }); 类为“someClass”的所有元素都有一个parentNode <li c

我正在尝试使用

$(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>
  • 我不知道哪里出了错。我做错了什么


    --David

    试着这样做:

    $(this).parent().attr('data-element');
    
    有关.parent()等函数的更多信息,请参阅JQuery文档的遍历部分: 你应该这样做

     $(this).parent().attr('data-element')
    

    因为不能使用jQuery对非jQuery对象调用
    attr()
    ,所以应该:

    $(this).parent().attr('data-element');
    
    如果不使用jquery,这将是:

    this.parentNode.getAttribute("data-element")
    

    在同一行代码中混合使用jQuery和普通javascript,这是行不通的。您可以使用:

    $(this).parent().attr('data-element');   // jQuery
    

    parentNode
    不是jQuery对象的属性,因此不能将两者混合使用。获取父项的jQuery方法是
    .parent()

    我更喜欢使用:

    var item = $(this);
    
    var parent = item.closest(".element"); //using the class for selection
    
    //and then use parent.attr('data-element')
    

    使用jQuery中的parent()代替parentNode。parentNode来自简单javascript,不适用于jQuery元素
    var item = $(this);
    
    var parent = item.closest(".element"); //using the class for selection
    
    //and then use parent.attr('data-element')