javascript - 事件点击 href <a> 标签

标签 javascript jquery ajax magento jquery-events

<分区>

我在这里有一个关于 Javascript 事件的问题。我有一个 <a>像这样的标签:

<a id='aTag' href='http://example.com'>Click to redirect</a>

然后我调用一个事件:

<script>
$('#aTag').click();
//or
$('#aTag').trigger('click');
</script>

它不会将我重定向到 http://example.com .我试图添加 onClick() <a> 中的事件像这样的标签:

<a id='aTag' href='http://example.com' onclick='alert("Event happened");'>Click to redirect</a>

然后调用.click()事件。它告诉我 alert("Event happened") ;

谁能告诉我如何调用 .click()正确事件,或使用 href 问题更正此重定向在那<a>标签?

在我的业务中,我只需要一个 <a>标签,所以不带 window.openwindown.location .

最佳答案

说明

重定向只有在用户直接点击链接时才会发生。程序化或延迟的 click 触发器不起作用。

另一种方法是:

  • 直接更改window.location
  • 在新标签页/窗口中打开链接

改变window.location

window.location="http://wherever.you/want/to/g0";

 window.location=$('a.selector').attr('href'); // to use a link's address

新标签/窗口

您不能以编程方式(click()trigger)打开新标签页/窗口或重定向。他们被(广告)屏蔽了。自动

因此,新标签页/窗口的打开始终必须由用户操作触发。 (否则我们将永远充满弹出式广告)

因此,首先,请确保您的 js 是在用户事件上执行的,然后您应该能够使用 window.open

JsFiddle example

html:

<a href="//google.com" target="blank">new tab google</a>

<button class="user">user triggered</button>
<button class="programatic">programatic</button>

js:

$('a').on('click', function(e) {
    console.log('clicked', e);
    // unfortunately although we simulated 
    // the click on the <a/> , it will still 
    // not launch a new window - idk why.
    // therefore we can use the line below
    // to open the <a>'s href in a new tab/window
    // NOTE: this will only occur if the execution was
    // triggered by the user
    window.open(e.currentTarget.href);
});

var simulateClick = function(origEv) {
    var e = $.Event("click");
    e.ctrlKey = true;
    e.metaKey = true;
    e.originalEvent = origEv;
    $('a').trigger(e);
};

$('button.user').on('click', function(e) {
    // this call will actually open a window
    simulateClick(e);
});

$('button.programatic').on('click', function(e) {
    // this will result in a blocked popup
    $.get('/someurl').always(function() {
        // executes the method after a non-user event
        // results in blocked popup
        simulateClick(e);
    });
});

// this will result in a blocked popup
setTimeout(simulateClick, 1000);

关于javascript - 事件点击 href <a> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24548630/

相关文章:

javascript - 在 tableViewRow 中交换图像

javascript - jQuery:如何在尚未添加到 DOM 的元素上调用 jQuery 插件函数?

javascript - 在YouTube视频上使用带有fancybox的jQuery…但是Youtube控件不起作用?

javascript - 单击按钮后如何隐藏 anchor 元素?

jQuery UI 对话框 + Ajax 在 IE 6-7-8 上失败

php - 单独项目的下载计数器,但不同语言的下载计数器相同

javascript - 使用push函数将项目添加到数组中

javascript - 我的网页如何在没有点击事件的情况下仅使用 JavaScript 下载服务器上的文件

javascript - .done 不是函数

javascript - 如何使用 javascript/jquery 获取 iframe 的 URL 的 anchor 属性?