2014-01-10 57 views
0
<a href="http://www.somesite.com/sometrack.mp3" onclick="trackDownload('sometrack.mp3')"> 
    <button> Download </button> 
</a> 

我需要触发下载以及触发JavaScript函数trackDownload()。在音频下载链接上触发点击事件

trackDownload()是一个Ajax函数,理想情况下完成ajax调用后我们需要触发下载。

但不幸的是,这并没有发生。我相信它是因为该页面导航到下载链接。

是否有解决方法?我确实想到了一个JS功能,可以跟踪并重定向到链接。但想到第二个意见堆栈溢出专家。

回答

0

感谢所有的答案,它绝对没有启发我的最佳解决方案追捕。

@ Raunak的答案是没有找到我的问题的解决方案,但是,从锚标记使用

onclick="return false;" 

然而是不是正确的解决方案。因为它在Jquery dom引擎上触发了多个事件。

我真正需要的是防止链接的默认操作并调用ajax函数。

所以我在点击事件后添加了event.preventDefault();,接着是ajax函数,并在ajax调用的成功事件之后加载了下载地址。

$('#container a').click(function(event){ 
    event.preventDefault(); // This is what is different from @Raunak's answer 

    var el = $(this); // $(this).href may not be valid inside ajax function 
         // due to disambiguation of $(this) 
         // hence storing the element on a local veriable 

    $.post('http://someURL', { info: someInfo}) 
    .done(function(data) { 
     location.href = el.attr('href'); 
    }); 

    }); 
+0

假设链接位于元素ID #container内。 –

0
<a href="#" onclick="trackDownload('sometrack.mp3')"> 
    <button> Download </button> 
</a> 

<script> 
    function trackDownload(file) 
    { 
     // other function body here.... 
     window.open('http://www.somesite.com/'+file, '_blank'); 
    } 
</script> 
1

你可以做的是重视甚至按钮,而不是如果锚链接和return false

HTML

<a href="http://www.somesite.com/sometrack.mp3" onclick="return false;"> 
    <button id="button"> Download </button> 
</a> 

jQuery的

$(function() { 
    $('#button').on('click', function() { 
     trackDownload(); 
     alert($(this).parents('a').attr('href')); 
     window.location = $(this).parents('a').attr('href'); 
    }); 
}); 

function trackDownload() { 
    alert('Track is getting download'); 
} 

,如果你想到o笔在新标签中使用window.open($('#myanchor').attr('href'));

DEMO

作为指定trackDownload()中的注释,这是AJAX功能,你可以做什么是

$('#button').on('click', function() { 
     trackDownload($(this).parents('a')); // pass your link to this function 

    }); 

function trackDownload(element) { 
    $.ajax(
     url: 'yoururl', 
     type: 'post', 
     ... // all other parameter you want to pass 
     success: function() { // success when ajax is completed 
      window.location = element.attr('href'); // change url only when ajax is success 
     } 
} 

但是,如果要附加单击事件链接,然后你可以做同样的事情,只需要连接事件

<a id='music' href="http://www.somesite.com/sometrack.mp3" onclick="return false;"> 
    <button> Download </button> 
</a> 

JS

$(function() { 
     $('#music').on('click', function() { 
      trackDownload(); 
      alert($(this).attr('href')); 
      window.location = $(this).attr('href'); 
     }); 
    }); 

您也可以看看这个对于更多的选择How can I simulate a click to an anchor tag?

+0

trackDownload()是一个Ajax函数,因此需要一些时间才能完成。由于这一个触发window.location = $(this)。ATTR( 'href' 属性);在同一个线程中,链接加载并trackDownload()中途中断。 –

+0

检查ajax场景的更新答案 –