簡體   English   中英

獲取父節點的屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM