我正在使用Jquery 1.7.2。 我希望在鼠标点击网页上的任何html元素时获得如下所示的输出。
假设Html代码是:>
<div id ="mySDiv" class="FT">
<div class="product">
<a href="#">Try</a>
<a href="#">catch</a>
<a href="#">Throw</a>
</div>
</div>
当我点击锚标记“catch”上的html元素时,上面代码的输出将是
DIV#mySDIV.FT DIV.product A.eq(2)
我可以输出到下面
DIV#mySDIV.FT DIV.product
为实现输出而编写的代码
$(document).click(function (e) {
e.preventDefault();
var $parents = $(e.target).parentsUntil('[id]');
var tagNames = $parents.add($parents.parent())
.map(function () {
myCssSelector;
var tagId = $(this).attr("id"); ;
if (tag) {
myCssSelector = this.tagName + "#" + tagId;
var myClassName = $(this).attr("class");
if (myClassName) {
myCssSelector = myCssSelector + "." + myClassName;
}
else {
myCssSelector = myCssSelector + " ";
}
}
else {
myCssSelector = this.tagName;
var myClassName = $(this).attr("class");
if (myClassName) {
myCssSelector = myCssSelector + "." + myClassName;
}
else {
myCssSelector = myCssSelector + " ";
}
}
return myCssSelector;
}).get().join(',');
console.log(tagNames);
});
我无法横向移动孩子并计算点击元素的兄弟节点
请帮帮我
答案 0 :(得分:3)
http://jsfiddle.net/earlonrails/LCUzy/9/
$('*').click(function(e){
var tagId = $(this).attr("id");
if (tagId) {
myCssSelector = this.tagName + "#" + tagId;
var myClassName = $(this).attr("class");
if (myClassName) {
myCssSelector = myCssSelector + "." + myClassName;
} else {
myCssSelector = myCssSelector + " ";
}
} else {
myCssSelector = this.tagName;
var myClassName = $(this).attr("class");
if (myClassName) {
myCssSelector = myCssSelector + "." + myClassName;
} else {
myCssSelector = myCssSelector + " " + $(this).index();
}
}
console.log(myCssSelector);
});