如何为 DOM 元素生成唯一的 css 选择器? [英] How to generate unique css selector for DOM element?
问题描述
我需要为元素生成唯一的 css 选择器.
特别是,我有 onclick 事件处理程序,应该记住什么目标元素单击并将此信息发送到我的服务器.有没有不做 DOM 修改的方法呢?
I need to generate unique css selector for elements.
Particularly, I have onclick event handler that should remember what target element
was clicked and send this info to my server. Is there a way to do it without doing DOM modifications?
附言我的 javascript 代码应该在不同的
上运行3-rd 方网站,所以我不能对 html 做出任何假设.
P.S. my javascript code supposed to be run on different
3-rd party websites so I can't make any assumptions about html.
推荐答案
为了简单起见,假设您有一个链接列表:您可以简单地传递所有元素集合中触发元素的索引
let say you have a list of links for the sake of simplicity: you can simply pass the index of the triggering element in the collection of all elements
<a href="#">...</a>
<a href="#">...</a>
<a href="#">...</a>
js(jQuery 1.7+,我用.on()
否则用bind()
)函数即可
the js (jQuery 1.7+, I used .on()
otherwise use bind()
) function can be
var triggers = $('a');
triggers.on('click', function(e) {
e.preventDefault();
var index = triggers.index($(this));
/* ajax call passing index value */
});
这样,如果您单击第三个元素,传递的索引值将为 2.(基于 0 的索引);当然,只要代码(DOM)没有改变,这就是有效的.稍后您可以使用该索引为该元素创建一个 css 规则,例如使用 :nth-child
so that if you click on third element index value passed will be 2. (0-based index);
of course this is valid as long as the code (the DOM) doesn't change. Later you can use that index to create a css rule to that element e.g. using :nth-child
否则,如果您的每个元素都有不同的属性(例如 id),您可以传递该属性
Otherwise if each one of your elements have a different attribute (like an id) you can pass that attribute
JsFiddle 示例:http://jsfiddle.net/t7J8T/
example on JsFiddle : http://jsfiddle.net/t7J8T/
这篇关于如何为 DOM 元素生成唯一的 css 选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!