我在这里有一个关于 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.open
或 windown.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
。
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);