1

我正在使用 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);
    });

我无法在子节点上进行横向计算并计算单击元素的兄弟节点

请帮帮我

4

1 回答 1

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);
});
​
于 2012-05-12T07:32:43.713 回答