【问题标题】:Trigger function and open URL at the same time同时触发函数和打开URL
【发布时间】:2015-07-07 20:15:49
【问题描述】:

我正在创建一个计数器来计算对锚标记的点击次数。我还需要同时打开 URL。我尝试了下面的代码。页面在函数执行前被重定向。

有没有更好的方法来做到这一点?

代码:

$(document).ready(function () {
 var $res = $('#counter').text($.cookie('link-count') || 0)
    
    $('a').click(function () {
        var count = parseInt($.cookie('link-count'), 10) || 0;

        count++;
        if (count > 10) {
            $(this).attr("href", "https://www.yahoo.com");
        }
        $.cookie('link-count', count);
        $res.text(count);
        location.href = $(this).attr("href");
        
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="www.google.com">Google</a>
<div id="counter">0</div>

【问题讨论】:

  • 您的浏览器控制台是否出现任何错误?您是否包含了 jQuery.cookie 插件?您可能会发现 preventDefault() 很有用。
  • 当我使用 href="#" 时,该功能有效,但我希望 URL 也可以打开。不,我没有收到任何错误
  • 是的,尝试click(function (e) { e.preventDefault(),然后在完成操作后使用location.href = $(this).attr("href") 转到目标站点
  • 不,它不起作用。 URL 未打开
  • 也可以试试mousedown 而不是click

标签: javascript jquery click anchor counter


【解决方案1】:

var linkCount;
$(document).ready(function () {
 var $res = $('#counter').text(linkCount || 0)
    
   $('a').click(function (e) {
      
        e.preventDefault();
      
        var count = parseInt(linkCount) || 0;

        count++;
        if (count > 10) {
            $(this).attr("href", "https://www.yahoo.com");
        }
        linkCount = count;
        $res.text(count);
        location.href = $(this).attr("href")
      
        
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="www.google.com">Google</a>
<div id="counter">0</div>

【讨论】:

  • 由于安全问题不能使用cookies或localStorage,所以用全局变量模拟
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多