如何使用javascript来模拟鼠标点击

时间:2012-02-12 22:11:32

标签: javascript html click mouseevent

我花了2天时间用谷歌搜索一个跨浏览器的解决方案来模拟html< a >上的鼠标点击,但还没有找到一个。

//-- REGARDING javascript's fireEvent (for IE browsers)
var lvs_event = 'click' ;              
var lvo_event = document.createEventObject();             
argo_target.fireEvent( 'on' + lvs_event , lvo_event );
//-------- does not work on either my winXP IE6 or my winVista IE8


//-- REGARDING javascript's dispatchEvent (for non-IE browsers)
var lvo_event = argo_target.ownerDocument.createEvent('MouseEvents') ;
lvo_event.initMouseEvent( 'click' , ... ) ;
argo_target.dispatchEvent( lvo_event ) ;
//-------- does not work on winVista FF3.6

//-- REGARDING inserting location.href
<a href    = '...'
   target  = '...'
   onclick = '...;location.href = this.href;...'
>
<script>
my_a.onclick();
<\/script>
//-------- works consistently BUT literally calls the onclick handler, ignoring all other <_a_> properties such as href and target

//-- REGARDING various jQuery solutions
$('#my_a').trigger('click');
//OR
$('#my_a').click();
//-------- does not work on any browsers (jQuery IS successfully being used for other features however)

我的目标:对于一个闪存按钮,将消息传递给js,然后将其自动化为&lt; a &gt;点击过程。

我当然可以让flash调用js,从js获取必要的html信息并将其返回到flash,然后可以执行as3 geturl,但我更愿意与现有的html环​​境进程绑定。

我目前正在测试各种版本的ff,即opera,safari(for win),winXP和winVista上的chrome。

1 个答案:

答案 0 :(得分:1)

如果你想跟踪触发器上的url,那么你必须在函数中这样说:

<强> HTML:

<a id="link" href="http://google.com">Link</a>
<a id="trigger" href="#">Trigger link</a>  

<强> JQ:

$('#link').click(function(){ alert('hey'); });
$('#trigger').click(function(){
    var $link = $('#link');
    $link.trigger('click');
    // window.location.href = $link.attr('href');
    window.open($link.attr('href'), '_blank'); // Popup blockers might block this
});