我的要求是当用户在元素上移动鼠标时 我想获得该元素的选择器。 让我说我当前的元素是$(this) 和$(this)没有任何类和ID。 现在我想通过JQUERY获取此元素的引用 或CSS选择器。注意:限制是我不能分配$(元素) 任何身份或类别。
如果您访问femtoo.com监控网页。
我想在下图中突出显示选择器。
我的要求与此完全相似。
任何帮助请我是Jquery的新人。
答案 0 :(得分:1)
您需要遍历DOM树从节点到根元素,但如果元素没有ID属性,则创建明确的选择器并不容易。
您还没有发布任何代码,因此您不应该真正期待解决方案,但我之前已经做过类似的事情并且可能会在此处发布。
演示:http://jsfiddle.net/N7Rrh/2/
document.documentElement.addEventListener('click', function(e){
var node = e.target,
parents = [],
selector = [];
/* Build a list of ancestors up to the documentElement */
while( node.parentNode ){
parents.push( node );
node = node.parentNode;
}
/* go over the ancestors list in reverse order, skipping the last two (HTML and BODY elements).
use i = parents.length - 2 to include the BODY element. */
for( var i = parents.length - 3; i >= 0; i-- ){
var nodename, id, classname, siblings, index, selectorstring;
// assign currently processed element to the node variable
node = parents[i];
// get the tag name, make it lowercase
nodename = node.nodeName.toLowerCase();
// if given node has an id let's use it as it's the best choice
if( node.id ){
selectorstring = nodename + '#' + node.id;
}
// otherwise get as much info as needed
else {
// class name:
classname = node.className
// remove leading and trailing white space
.replace(/^\s*|\s*$/g,'')
// replace remaining spaces with dots
.replace(/\s+/g,'.');
// nth-child / first child.
// get all the siblings (children of parent node)
// and turn the nodeList to an Array
siblings = [].slice.call( parents[i+1].children );
// ... and find current node in that array
index = siblings.indexOf( node );
// now combine the info:
selectorstring = nodename +
// add leading dot to the class name if there's a class name
(classname != '' ? '.' + classname : '') +
// append first-child or nth-child(n) string
(index===0?':first-child':':nth-child('+index+')');
}
selector.push( selectorstring );
}
// now join the selectors of particular elements as direct child selectors
selector = selector.join('>');
console.log( selector );
return selector;
});
答案 1 :(得分:0)
如果你正在使用任何事件处理程序可能会在这里关注..你将获得var this
中该文本框的dom引用,然后你可以调用jQuery传递这个
$(this);
答案 2 :(得分:-1)
不申请任何课程: -
$(this).css('border','solid 1px red');