我的要求是當用戶在元素上移動鼠標 我想獲取該元素的選擇器。 讓我說當前元素是$(this) 和$(this)沒有任何類和ID。 現在我想要稍後通過JQUERY 或CSS選擇器來獲取此元素的引用。注意:限制是我不能指定$(元素) 任何id或class。
如果您訪問femtoo.com監控網頁。 我想在下圖中突出顯示的選擇器。 我的要求與此完全相似。 任何幫助,請我在Jquery新。
我的要求是當用戶在元素上移動鼠標 我想獲取該元素的選擇器。 讓我說當前元素是$(this) 和$(this)沒有任何類和ID。 現在我想要稍後通過JQUERY 或CSS選擇器來獲取此元素的引用。注意:限制是我不能指定$(元素) 任何id或class。
如果您訪問femtoo.com監控網頁。 我想在下圖中突出顯示的選擇器。 我的要求與此完全相似。 任何幫助,請我在Jquery新。
您需要遍歷從根元素節點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;
});
如果您正在使用的任何事件處理程序,可以在這裏集中..你會得到在var該文本框的DOM參考this
那麼你可以調用的jQuery通過這個像
$(this);
沒有施加任何類: -
$(this).css('border','solid 1px red');
您需要'this' –
我得到的這個參考。但我不知道如何生成 選擇器。如果$(this)有一個#Id,但是如果它不包含 有Id和Uniqe類名,那麼這很好,那麼我想生成一個選擇器,這有助於稍後識別此幫助。 –
你可以訪問femtoo.com嗎? 在femtoo用戶來選擇一個像螢火蟲然後femtoo的元素 生成該元素的CSS選擇器,如上圖所示。 –