When use code below in script always get null for e

var e = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();

But use this command in Chrome console, e could get correct value, why this happens?

Here are full code of js file and html file

test.js

function testClick(xpath){
var e = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();
// var a = e.iterateNext();
if(document.createEvent){
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, false);
    e.dispatchEvent(event);
}
else if(document.createEventObject){
    e.fireEvent('onclick');
}
}


var xpath = "(//a[@href='./detail.html'])[1]";
setTimeout(testClick(xpath), 3000);

html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <script type="text/javascript" src="../js/test.js"></script>
</head>
<body>
    <ul>
        <li class="carmen-li"><a href="./detail.html">1</a></li>
        <li><a href="./detail.html">2</a></li>
        <li><a href="./detail.html">3</a></li>
    </ul>
</body>
</html> 
有帮助吗?

解决方案

Problem resolved.

This one, code below, works, seems can not call a method with parameter in window.onload directly.

When call method with parameter in window.onload, it will execute this method before window.onload, so the element didn't complete loading when the method is executing, so it will return null.

function testClickWithParam(xpath){
    var e = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();

    if(document.createEvent){
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, false);
        e.dispatchEvent(event);
    }
    else if(document.createEventObject){
    e.fireEvent('onclick');
    }
}

function testClickLink(){
    var xpath = "(//a[@href='./detail.html'])[1]";
    console.log(window.location.href);
    testClickWithParam(xpath);
}


window.onload = testClickLink;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top