【问题标题】:Random redirrect after the page is loaded/clicked页面加载/点击后随机重定向
【发布时间】:2014-02-24 00:32:59
【问题描述】:

我正在开发 ASP.NET Razor v2 网站,现在我有一个链接可以帮助我将用户发送到我将其作为列表的随机 url,它看起来像这样;

@{
    List<string> UrlList = new List<string>();
UrlList.Add("http://example1.com/");
UrlList.Add("http://example2.com/");
UrlList.Add("http://example3.com/");
    Random r = new Random();
    int index = r.Next(UrlList.Count);
    string randomUrl = UrlList[index];
}

<a href="@randomUrl">A Random Link</a>

当我将鼠标悬停在“随机链接”上时,我看到了列表中的一个链接。

有没有办法在页面加载后将用户重定向到 URL?

简单地说; 点击“随机链接” -> 加载另一个页面 -> 重定向到列表中的链接。

【问题讨论】:

  • 您希望用户即使不点击链接也被重定向到页面?
  • 不,我希望用户在点击链接后被重定向。
  • 它应该被重定向,因为它是一个锚标记。你看到了什么行为?
  • 它从列表中打开一个随机链接,但如果我点击 5 次相同的链接,我希望它在我点击链接后随机化 URL,所以当我点击 5 次时它应该是 5随机网址。
  • 你需要重新加载你的页面,它会生成随机链接作为锚标签目标网址。

标签: asp.net razor-2


【解决方案1】:

看起来你需要在用户点击这个时重新加载目标网址。所以你应该

<a id="aRand" target="_blank" href="http://www.google.com">A Random Link</a>

现在在您的 javascript 中,当用户单击链接时,获取随机数并从 js 数组中读取链接并更新单击的锚标记 href 属性。

$(function(){
  var itemArr=["http://a.com","http://b.com","http://c.com"];

  $("#aRand").click(function(e){

     var randomNum=getRandom(0,itemArr.length);   
     var targetUrl=itemArr[randomNum];
     $(this).attr("href",targetUrl);

  });

});

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

您可以使用 ajax 请求从服务器操作方法中获取它,而不是对数组进行硬编码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2018-01-25
    • 2015-08-12
    相关资源
    最近更新 更多