如何获取 X/HTML 文件中元素的 xpath [英] How do i get the xpath of an element in an X/HTML file

查看:29
本文介绍了如何获取 X/HTML 文件中元素的 xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Xpath 的初学者,想知道是否有任何方法可以获取 javascript/jquery 中元素的 xpath.我需要一种绝对的方法来识别元素,我知道 Xpath 用于此,但不知道如何.

I am a beginner to Xpath and was wondering if there is any way to get the xpath of an element in javascript/jquery. I need an absolute way to identify an element and I knw Xpath is used for this,but can't figure how.

场景是我有一个元素的 jquery 引用.我希望它的 xpath 在鼠标单击时存储在数据库中.有了 jquery 引用后,如何获取 HTML 元素的 Xpath.我需要能够稍后将 Xpath 转换为绝对元素

The scenario is that I have a jquery reference of an element. I want its xpath to store in a database on mouse click. How do I get the Xpath of an HTML Element once I have a jquery reference. I need to be able to translate the Xpath into an absolute element later

function clickTrack(event){
offset=event.pageX;
var xpath=getXpath(this);//I need the xpath here
data={'xpath':xpath,'offset':offset};

}

推荐答案

您可以从我曾经写过的 XPath 工具中提取此功能:

You can extract this functionality from an XPath tool I once wrote:

http://webkitchen.cz/lab/opera/xpath-工具/xpath-tool.js

给你:

function getXPath(node) {
    var comp, comps = [];
    var parent = null;
    var xpath = '';
    var getPos = function(node) {
        var position = 1, curNode;
        if (node.nodeType == Node.ATTRIBUTE_NODE) {
            return null;
        }
        for (curNode = node.previousSibling; curNode; curNode = curNode.previousSibling) {
            if (curNode.nodeName == node.nodeName) {
                ++position;
            }
        }
        return position;
     }

    if (node instanceof Document) {
        return '/';
    }

    for (; node && !(node instanceof Document); node = node.nodeType == Node.ATTRIBUTE_NODE ? node.ownerElement : node.parentNode) {
        comp = comps[comps.length] = {};
        switch (node.nodeType) {
            case Node.TEXT_NODE:
                comp.name = 'text()';
                break;
            case Node.ATTRIBUTE_NODE:
                comp.name = '@' + node.nodeName;
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                comp.name = 'processing-instruction()';
                break;
            case Node.COMMENT_NODE:
                comp.name = 'comment()';
                break;
            case Node.ELEMENT_NODE:
                comp.name = node.nodeName;
                break;
        }
        comp.position = getPos(node);
    }

    for (var i = comps.length - 1; i >= 0; i--) {
        comp = comps[i];
        xpath += '/' + comp.name;
        if (comp.position != null) {
            xpath += '[' + comp.position + ']';
        }
    }

    return xpath;

}

如果您希望它也能在 IE 中运行,则可能需要进行一些更改.

It might need some changes if you want it to work in IE as well.

这篇关于如何获取 X/HTML 文件中元素的 xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆