Href到Onclick重定向

Href to Onclick redirect

本文关键字:重定向 Onclick Href      更新时间:2023-09-26

我通过社区研究了这个话题,尽管我找不到答案。我正在使用Bronto的直接添加功能(尝试使用它),文档不是很好。

总之,href链接为电子邮件列表中的用户订阅。唯一的问题是这个链接打开了一个新页面。当我希望用户停留在同一页面上时。我想在点击链接时进行重定向,但我不确定这是否有效。

我试过这个:

 //Html
<a id="subscription" href="http://example.com">Subscribe</a>
 // Jquery
  $("#emailsubscribe").click(function(e){
          e.preventDefault();//this will prevent the link trying to navigate to another page
          //do the update
          var href = "http://example.com";
          //when update has finished, navigate to the other page
          window.location = "href";
   });

目标是,我试图让用户点击链接,订阅他们的电子邮件列表,但立即将他们重定向回,而不打开另一个窗口。

您正在寻找AJAX。这允许您在不实际导航到页面的情况下发出请求。由于您使用的是jQuery

$("#emailSubscribe").click(function (e) {
  e.preventDefault();
  $.get("http://www.myurl.com", function (data) {
      //All done!
  });
});

您有3个选项:

  1. 执行AJAX请求以订阅用户

$('#emailsubscribe').on('click', function () { $.get('/email-subscribe/' + USER_ID, function () { // redirect goes here window.location = 'REDIRECT_URL'; }); });

  1. 使用iframe,当iframe加载完毕时,关闭iframe(丑陋、粗糙、不推荐)

  2. 让订阅页面重定向用户返回。Aka做常见的消息"你已经订阅了。5秒钟后重定向回来…"。你需要将重定向链接传递到订阅页面,也就是

    window.location='/subscribe/USER_ID?redirect_to=/my重定向页面'

您需要引用var,而不是键入另一个字符串来重定向。

//Html
<a id="subscription" href="http://example.com">Subscribe</a>
// Jquery
$("#emailsubscribe").click(function(e){
          e.preventDefault();//this will prevent the link trying to navigate to another page
          //do the update
          var href = "http://example.com";
          //when update has finished, navigate to the other page
          window.location = href; //<<<< change this.
});