당신은 루트 요소에 대한 노드에서 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;
});
당신이 필요합니다 'this' –
나는이의 참조를 얻었다. 하지만 난 선택기를 생성하는 방법을 모르겠습니다. $ (this) # Id를 가지고 있지만 괜찮지 않다면 에 Id 및 Uniqe 클래스 이름이 있으면 나중에이 도움말을 식별하는 데 도움이되는 선택기를 생성하고 싶습니다. –
femtoo.com을 방문 할 수 있습니까? femtoo 사용자의 은 firebug와 같은 요소를 선택한 다음 femtoo 위의 그림과 같은 요소의 CSS 선택기를 생성합니다. –