【发布时间】:2012-04-03 20:25:58
【问题描述】:
我有一个页面,里面有几个链接都是这样的:
<a href="/" class="answer-item" rel="0">10</a>
我想使用click() 函数来模拟用户点击其中一个,但在我的测试中似乎不起作用。
//Evaluate a mathematical expression from another part of the page
var numberAnswer = eval(document.getElementById("question-title").getElementsByTagName("b")[0].innerHTML);
//Builds an array with the links that may match the expression
var choices = document.getElementsByClassName('answer-item');
//Iterates through array to find a match then clicks it
for(var i in choices){
if(choices[i].innerHTML == numberAnswer){
choices[i].click();
break;
}
}
我确定choices[i] 是正确的元素。
Firefox 什么都不做,Opera 什么也不做,并且 click() 在 Chrome 中不可用(我认为)。
另外,我尝试以这种形式使用dispatchEvent():
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
choices[i].dispatchEvent(evt);
这显然在 Firefox 和 Chrome 中返回了true,但没有改变任何东西。
最麻烦的部分是只有href 属性的链接与.click() 配合得很好。
【问题讨论】:
标签: javascript html click dom-events