ホームページ > ウェブフロントエンド > jsチュートリアル > jQuery要素の階層パスを取得します

jQuery要素の階層パスを取得します

William Shakespeare
リリース: 2025-03-08 00:13:10
オリジナル
535 人が閲覧しました

このjQuery関数は、DOMツリー内の要素の階層パスを取得します。 それは、ルートに達するまで親要素を横断します。

jQuery Get Hierarchy Path of Element

コア機能は、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
    }
});
ログイン後にコピー
この改善されたバージョンは、潜在的な問題に対処しています:

  • より明確な変数名:より多くの記述変数名(の代わりに)を使用します。 currentElementNamecurエラー処理:
  • 再帰コールの前に
  • を使用して親要素の存在を明示的にチェックします。要素が既にルートにある場合はエラーを防ぎます。 パス構築:.lengthより堅牢なパス構築、IDのない要素の正しい間隔と処理を確保します。
  • パストリミング:
  • 不要なHTMLチェックを削除:元のコードには、削除されたものが混乱している可能性があり、誤っている可能性があります。 .trim()この改訂された関数は、jQueryコンテキスト内の任意の要素の階層パスを取得するためのより信頼性が高く効率的な方法を提供します。

以上がjQuery要素の階層パスを取得しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート