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

前端 未结 2 621
离开以前
离开以前 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条回答
  •  猫巷女王i
    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/

提交回复
热议问题