运行功能然后按链接

Tur*_*nip 10 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>
Run Code Online (Sandbox Code Playgroud)

如何link#main_nav单击内部之前运行函数,然后再执行link

以下不起作用,因为在运行函数之前遵循链接.

$('#main_nav a').click(function() {
    // Some Function
});
Run Code Online (Sandbox Code Playgroud)

编辑

我实际上是在点击链接时尝试使用JQuery cookie插件清除cookie.我不确定这是否相关.

清除cookie代码是:

$.cookie('TMMenu', null);
Run Code Online (Sandbox Code Playgroud)

TMMenu是正确的名称,并加载插件.

编辑

对不起大家.问题实际上是JQuery Cookie插件文档.

$.cookie('TMMenu', null); 
Run Code Online (Sandbox Code Playgroud)

如自述文件中所述似乎不起作用.这样做:

$.cookie('TMMenu', null, { path: '/', expires: -5 });
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 29

更新:重新编辑:我看不出除下面#1以外的任何其他原因.

我能想到这个问题的两个答案:

  1. 您在#main_nav a元素存在之前运行jQuery代码,并且没有连接事件处理程序.将您的脚本放在HTML文件的底部,就在结束</body>标记之前,或者使用ready回调.

  2. 你正在处理程序中做异步,而不是看到它发生.这是因为只要事件处理程序返回,链接就会被跟踪 - 即使你的处理程序启动了一些异步操作.

以下是如何修复第二个(如果你把它放在最后或ready处理程序内):

$('#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;
    });
});
Run Code Online (Sandbox Code Playgroud)

(实时复制 | 来源)


pse*_*ant 6

这是您的操作方式。如果您event.preventDefault在点击处理程序回调中进行调用,它将阻止默认操作。然后使用window.open(url)或通过JavaScript跟踪链接window.location = url

纯Java范例

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();
});
Run Code Online (Sandbox Code Playgroud)

jQuery示例

$('#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();
});
Run Code Online (Sandbox Code Playgroud)

有关window.open和之间的区别的更多信息,请参见MDN window.location