问题描述
我需要为元素生成唯一的css选择器。
特别地,我有onclick事件处理程序,应该记住
被点击的目标元素,并将此信息发送到我的服务器。有没有办法做,而不做DOM修改?
I need to generate unique css selector for elements.
Particularly, I have onclick event handler that should remember what target elementwas clicked and send this info to my server. Is there a way to do it without doing DOM modifications?
P.S。我的JavaScript代码应该运行在不同的
第三方网站,所以我不能对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 code>否则使用
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. ;
当然这是有效的,只要代码(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
否则,如果每个元素都有不同的属性可以传递该属性
Otherwise if each one of your elements have a different attribute (like an id) you can pass that attribute
在JsFiddle上的示例:
example on JsFiddle : http://jsfiddle.net/t7J8T/
这篇关于如何为DOM元素生成独特的css选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!