如何在javascript中模拟点击?

时间:2009-11-19 19:42:48

标签: javascript jquery

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

3 个答案:

答案 0 :(得分:6)

使用element.click()可以轻松模拟元素上的点击; 无需安装9000行jquery库就可以模拟点击。如果你知道一个元素的ID,点击它就会这么简单:

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

如果没有id属性,获取要单击的元素会更难,但幸运的是有Xpath,因此获取并单击元素仍然可以在一行优雅的代码中完成。请注意,contains方法只需要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>

答案 1 :(得分:5)

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

答案 2 :(得分:2)

如果有人碰到这个寻找框架不可知方式来解雇任何HTML和鼠标事件,请查看此处:How to simulate a mouse click using JavaScript?