此jQuery函數檢索DOM樹中元素的層次路徑。 它會遍歷父元素,直到達到根。
>
核心功能封裝在getPath
>方法中,該方法擴展到jQuery對象原型。 該功能遞歸地在父元素上調用自己,直到滿足特定條件為止。
/* jQuery function to get the hierarchical path of an element */ jQuery.fn.extend({ getPath: function(path) { if (typeof path === 'undefined') path = ''; // Initialize path if undefined let currentElementName = this.get(0).nodeName.toLowerCase(); let id = this.attr('id'); // Add ID to path if available, handling the special case of an element with id 'browser' if (typeof id !== 'undefined') { if (id === 'browser') { return path; // Stop recursion if id is 'browser' } else { path = `${currentElementName}#${id} ` + path; // Add id to path } } else { path = `${currentElementName} ` + path; // Add element name to path } // Recursive call to parent element return this.parent().length ? this.parent().getPath(path) : path.trim(); // Return trimmed path if parent doesn't exist } });
這個改進的版本解決了潛在問題:
currentElementName
而不是cur
)。 .length
的父元素的存在,如果元素已經在root處,則可以防止錯誤
.trim()
>html.search
此修訂的功能提供了一種更可靠,更有效的方法,以在jQuery上下文中獲取任何元素的層次路徑。 以上是jQuery獲得元素的層次結構路徑的詳細內容。更多資訊請關注PHP中文網其他相關文章!