此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中文网其他相关文章!