模拟本机点击 [英] Simulate native click

查看:91
本文介绍了模拟本机点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在链接上触发click事件,然后,如果没有任何侦听器阻止默认值,则更改位置。

I need to trigger the click event on a link and then, if none of the listeners prevented the default, change the location.

这是我到目前为止所做的:

This is what I've got so far:

var $el = $('a#my_special_link');
var onClick = $el.attr('onclick');

// Hack to capture the event object
var ev_reference;
var ev_capture = function(ev) { ev_reference = ev; }
$el.bind('click', ev_capture);

// Don't leave out the onClick handler
if ( typeof onClick == 'function' )
    $el.bind('click', onClick);

$el.trigger('click');

// Clean up
$el.unbind('click', ev_capture);
if ( typeof onClick == 'function' )
    $el.unbind('click', onClick);

// Redirect if necessary
if ( ! ev_reference.isDefaultPrevented() )
  window.location = $el.attr('href');

欢迎任何改进建议。

PS:是的,它只是常规链接的工作方式,除了你可以在其间进行其他处理。

PS: Yes, it's just how a regular link would work, except you can do some other processing in between.

PPS :不,只需要执行$ el.trigger('click');将更改位置。

PPS: No, just doing $el.trigger('click'); will not change the location.

推荐答案

在此处输入代码将我的笔记提取到其他帖子:(另一种说法相同的基本内容)

enter code hereTo extract my notes to others posts: (another way to say same basic stuff)

      <a href="somewhere" id="mylink">MyLink</a> 
        <script>jQuery('#mylink').click(function(){
            // do whatever I want here, then redirect
             window.location.href = "http://stackoverflow.com";
        });
        function doClick(){
            jQuery('#mylink').trigger('click'); 
        };
        // trigger the redirect now
        doClick();
        </script>

EDIT1:@ comments:

@ comments:

如果你描述的其他返回false,你在那时,用false终止回调 - 所以你是正确的,但与这个处理程序无关。哪一次点击首先执行,另一次永远不会返回,如果它首先执行,那么这一次会重定向到另一次点击日志之前。

If the "other" you describe returns false, you at that point, terminate the callback with the false - so you are correct but has nothing to do with this handler. Which ever one hits first executes, and the other never does return, and this one redirects prior to the other one hitting the log if it executes first.

为了放置你登录,你把它放在我的地方

In order to put your log in, you put that where I have my

 "// do whatever I want here, then redirect"

评论
要删除其他事件,请仅与此绑定:

comment To remove the other event, then bind with this one only:

   <a href="somewhere" id="mylink">MyLink</a> 
        <script>jQuery('#mylink').unbind('click').bind('click', function(){
            // do whatever I want here, then redirect
             window.location.href = "http://stackoverflow.com";
        });
        function doClick(){
            jQuery('#mylink').trigger('click'); 
        };
        // trigger the redirect now
        doClick();

这篇关于模拟本机点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆