Javascript 运行函数,然后跟随链接
我似乎找不到一个我在这里尝试做的例子,但我相信这是可能的 考虑以下几点:Javascript 运行函数,然后跟随链接,javascript,jquery,hyperlink,Javascript,Jquery,Hyperlink,我似乎找不到一个我在这里尝试做的例子,但我相信这是可能的 考虑以下几点: <div id="main_nav"> <a href="/url/">LINK</a> <a href="/url/">LINK</a> <a href="/url/">LINK</a> <a href="/url/">LINK</a> </div> 编辑 我实际上是想
<div id="main_nav">
<a href="/url/">LINK</a>
<a href="/url/">LINK</a>
<a href="/url/">LINK</a>
<a href="/url/">LINK</a>
</div>
编辑
我实际上是想在点击链接时用JQuery cookie插件清除cookie。我不确定这是否相关 清除cookie代码为:
$.cookie('TMMenu', null);
TMMenu是正确的名称,插件已加载
编辑
对不起大家。问题其实出在汽车上
如自述文件中所述,似乎不起作用。这是:
$.cookie('TMMenu', null, { path: '/', expires: -5 });
这是你怎么做的。如果在单击处理程序回调中调用
event.preventDefault
,它将阻止默认操作。然后要通过Javascript跟踪链接,只需使用window.open(url)
或window.location=url
普通Javascript示例
document.querySelector('main#u nav a')。addEventListener('click',函数(事件){
//在跟随链接之前做一些事情
//从目标元素获取url(
更新:重新编辑:除了下面的#1之外,我看不到任何不起作用的原因
对于这个问题,我可以想出两个答案:
在#main_nav a
元素存在且没有连接事件处理程序之前运行jQuery代码。请将脚本放在HTML文件的底部,就在关闭
标记之前,或者使用
您正在处理程序中执行异步操作,但没有看到它发生。这是因为一旦事件处理程序返回,链接就会被跟踪,即使处理程序启动了一些异步操作
下面是修复第二个问题的方法(如果将其放在末尾或ready
处理程序中,则两者都可以):
(|)此代码没有问题。单击的主体将运行,然后链接将被跟踪。您看到了什么问题?听起来您需要某种回调。您是否试图在链接导航到之前执行异步行为,例如动画或AJAX请求?我实际上是在尝试清除coo带有“$.cookie('TMMenu',null);”的kie当链接被点击,但这似乎没有发生。我会标记你为提供了一个有趣的例子是正确的。问题实际上是我用来删除cookie的代码。许多thanks@3rror404:很高兴你发现它很有用!虽然我非常感谢该代表,但如果你发布自己的答案,说明它是什么,并且母鸡(48小时后)接受了它。如果你还没有接受,我会投赞成票。;-(或者你可以标记你的问题,请主持人删除它,因为它可能对其他人没有用处……)@T.J.Crowder此解决方案是否适用于已按ctrl键单击或右键单击并在新选项卡中打开的链接?@pdoherty926:否。使用上述代码的控件单击将被视为常规单击(因为我们没有检查控件键的状态)。我们可以检测到控件单击,但无法在异步回调中打开新选项卡(因为浏览器的弹出窗口阻止程序会阻止它,因为它不会直接响应用户事件)。而且右键单击“在新选项卡中打开”我们也无能为力
$.cookie('TMMenu', null);
$.cookie('TMMenu', null, { path: '/', expires: -5 });
document.querySelector('#main_nav a').addEventListener('click', function (event) {
// Do something before following the link
// Get url from the target element (<a>) href attribute
var url = event.target.href;
// Open the url in the current window. Set to "_blank" instead of "_self" to open in a new window.
window.open(url, '_self');
// Prevent default action (e.g. following the link)
event.preventDefault();
});
$('#main_nav a').click(function (event) {
// Do something before following the link
// Get url from the <a> href attribute
var url = $(this).attr('href');
// Open the url in the current window. Set to "_blank" instead of "_self" to open in a new window.
window.open(url, "_self");
// Prevent default action (e.g. following the link)
event.preventDefault();
});
$('#main_nav a').click(function(event) {
// Remember the link href
var href = this.href;
// Don't follow the link
event.preventDefault();
// Do the async thing
startSomeAsyncThing(function() {
// This is the completion callback for the asynchronous thing;
// go to the link
window.location = href;
});
});