Return XPath location with jQuery? Need some feedback on a function

前端 未结 2 618
离开以前
离开以前 2020-12-10 22:31

For the following project I will be using PHP and jQuery.

I have the following code:

$(\'*\').onclick(function(){

});

Once a user

相关标签:
2条回答
  • 2020-12-10 22:56

    You can use the .parents() method, to get all ancestors of the clicked element.

    $(document).delegate('*','click',function(){
      var path = $(this).parents().andSelf();
      return false;
    });
    

    and then extract the info you want.

    Use the .delegate method to handle the event, so you do not need to attach it to all elements. And also use the .andSelf() method to include in the path the item that was clicked as well.


    A more complete example

    $(document).delegate('*','click',function(){
        var path = $(this).parents().andSelf();
        var xpath='/';
        for (var i = 0; i < path.length; i++)
        {
            var nd = path[i].nodeName.toLowerCase();
            xpath += '/';
            if (nd != 'html' && nd != 'body')
            {xpath += nd+'['+ ($(path[i-1]).children().index(path[i])+1) +']';}
            else
            {xpath += nd;}                    
        }
        alert(xpath);
        return false;
    });
    

    Example with a test html to play at http://www.jsfiddle.net/gaby/hsv97/1/


    update with id and class shown as well : http://www.jsfiddle.net/gaby/hsv97/2/

    0 讨论(0)
  • 2020-12-10 23:00

    a fix to Gaby aka G. Petrioli

    added "nd" to children

    .children(nd)
    

    full:

    $(document).delegate('*','click',function(){
            var path = $(this).parents().andSelf();
            var xpath=''; // firebug xpath starts with '/html'
            for (var i = 0; i < path.length; i++) {
                var nd = path[i].nodeName.toLowerCase();
                if (nd =="tbody") continue;  // php DOMxpath ignores tbody? or browser fixes html?
                xpath += '/';
                if (nd != 'html' && nd != 'body')
                {xpath += nd+'['+ ($(path[i-1]).children(nd).index(path[i])+1) +']';} //! saving time ha?
                else
                {xpath += nd;}                    
            }
            alert(xpath);
            return false;
        });
    
    0 讨论(0)
提交回复
热议问题