この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
より堅牢なパス構築、IDのない要素の正しい間隔と処理を確保します。
.trim()
この改訂された関数は、jQueryコンテキスト内の任意の要素の階層パスを取得するためのより信頼性が高く効率的な方法を提供します。以上がjQuery要素の階層パスを取得しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。