简体   繁体   中英

How to rewrite a javascript function in jquery?

I have a javascript function to get the xpath of an element. I need to rewrite it in jquery. Please help. Below are my functions:

$("a").click(function(event) {
    getXPath($(this));
}

This is a jquery function call.

function getXPath(element) {
    if (element.id!=='')
        return './/*[@id='+ element.id +']';
    if (element===document.body)
        return element.tagName;
    var ix= 0;
    var siblings= element.parentNode.childNodes;
    for (var i= 0; i<siblings.length; i++) {
        var sibling= siblings[i];
        if (sibling===element)
            return getXPath(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']';
        if (sibling.nodeType===1 && sibling.tagName===element.tagName)
            ix++;
    }
}

I have this javascript function. But it returns xpath like .//*[id=@undefined] . Please help.

You must pass a DOM element to the function, which you can achieve eg as follows:

getXPath($(this).get(0));

If this refers already to a DOM element, you can use it directly instead of creating a jQuery object from it:

getXPath(this);

Even if you are using jQuery, this does not mean you have to use it for everything. Typically jQuery also introduces some overhead, but enhances readability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM