获取元素的jQuery选择器 [英] Getting a jQuery selector for an element

查看:105
本文介绍了获取元素的jQuery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在伪代码中,这就是我想要的.

In psuedo code, this is what I want.

var selector = $(this).cssSelectorAsString(); // Made up method...
// selector is now something like: "html>body>ul>li>img[3]"
var element = $(selector);

原因是我需要将此传递给外部环境,在该环境中,字符串是我交换数据的唯一方法.然后,该外部环境需要将结果以及要更新的元素一起发送回去.因此,我需要能够为页面上的每个元素序列化一个唯一的CSS选择器.

The reason is that I need to pass this off to an external environment, where a string is my only way to exchange data. This external environment then needs to send back a result, along with what element to update. So I need to be able to serialize a unique CSS selector for every element on the page.

我注意到jquery有一个selector方法,但是在这种情况下似乎不起作用.仅当对象是使用选择器创建的时才有效.如果该对象是使用HTML节点对象创建的,则无法使用.

I noticed jquery has a selector method, but it does not appear to work in this context. It only works if the object was created with a selector. It does not work if the object was created with an HTML node object.

推荐答案

我现在看到存在一个插件(我也想到了同样的名字),但这只是我编写的一些快速JavaScript.它不考虑元素的ID或类–.仅结构(并添加:eq(x)节点名称不明确的地方).

I see now that a plugin existed (with the same name I thought of too), but here's just some quick JavaScript I wrote. It takes no consideration to the ids or classes of elements – only the structure (and adds :eq(x) where a node name is ambiguous).

jQuery.fn.getPath = function () {
    if (this.length != 1) throw 'Requires one element.';

    var path, node = this;
    while (node.length) {
        var realNode = node[0], name = realNode.localName;
        if (!name) break;
        name = name.toLowerCase();

        var parent = node.parent();

        var siblings = parent.children(name);
        if (siblings.length > 1) { 
            name += ':eq(' + siblings.index(realNode) + ')';
        }

        path = name + (path ? '>' + path : '');
        node = parent;
    }

    return path;
};

这篇关于获取元素的jQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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