在脚本中使用下面的代码时,e 总是为 null
var e = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();
但是在 Chrome 控制台中使用这个命令,e 可以得到正确的值,为什么会发生这种情况?
这是js文件和html文件的完整代码
测试.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>