2009-11-19 42 views
0

其中一项功能是当用户点击某物时会发生某些事情。如何在不调用函数的情况下模拟此点击?如何模拟javascript中的点击?

+1

你想要达到什么样的purprose? – 2009-11-19 19:49:05

+0

是的,你是否想要导航到链接的'href'中的url? – 2009-11-19 19:55:16

回答

5

使用jQuery,你可以做$("#myElementId").click()模拟点击。

+0

+1为答案和jquery的迷人 – 2009-11-19 19:45:32

+2

真正的jquery是炸弹。 – 2009-11-19 19:47:01

+0

你也可以使用'trigger'(http://docs.jquery.com/Events/trigger) – Mottie 2009-11-19 20:31:04

6

的模拟元件上的点击容易与element.click()完成的; 没有必要安装一个9000行的jQuery库来模拟点击。如果你知道一个元素的ID,点击它会是这样简单:

document.getElementById('someID').click(); 

得到你想要点击一个元素是难上加难,如果没有id属性,但幸运的是Xpath的,因此让和点击一个元素仍然可以在一行优雅的代码中完成。请注意,包含方法只需要src属性的部分匹配。

document.evaluate(" //a[ contains(@src, 'someURL') ] ", document.body, null, 9, null). singleNodeValue.click(); 

或和,并且可以使用运营商,像这样:

document.evaluate(" //*[ contains(@id, 'someID') or contains(@name, 'someName') ] ", document, null, 9, null). singleNodeValue.click(); 

一个完整的多浏览器的例子可能看起来类似的东西。在IE8及以下版本中,如果你之后的元素没有id,你可以用document.getElementsByTagName('tagname');然后使用for循环来评估元素或其innerHTML的某个属性。

<html> 
<body> 
<input type='button' id='someID' value='click it' onclick='myAlert()' /> 

<p onclick="simulateClick()" >Click the text to simulate clicking the button above - the button will be automatically clicked in 3.5 seconds 

<script> 

function simulateClick(){ 
var button; 
try{ // Xpath for most browsers 
button = document.evaluate(".//input[ contains(@id, 'someID') ] ", document.body, null, 9, null). singleNodeValue; 
}catch(err){ // DOM method for IE8 and below 
button = document.getElementById("someID"); 
} 

if (button) { button.click(); } 
else { alert("No button was found, so I can't click it"); } 

} 

function myAlert(){alert("button clicked")} 

setTimeout(simulateClick, 3500); 

</script> 
</body> 
</html>