使用 JavaScript 正确创建指向包含随机数的 URL 的链接

Make correctly a link to an URL containing a random number with JavaScript

本文关键字:随机数 包含 URL 链接 JavaScript 创建 使用      更新时间:2023-09-26

我正在管理一个论坛,我想在我的网站上放置一个访问随机用户个人资料页面的链接。

假设访问个人资料页面的 URL 格式为:http://www.mypage.com/#m=Profile&user_id=XXXXX(其中 XXXXX 是一个数字),我尝试输入以下 HTML 代码:

<a target="_blank" href="http://www.mypage.com/#m=Profile&user_id=" onclick="this.href=this.href.split('?')[0]+(Math.floor(Math.random()*(75800000-59438709))+59438709)">Open a random profile. Click here!</a>

它工作正常,当我单击此链接时,它会访问随机配置文件。但问题是:如果我再次单击该链接,它会访问具有新的随机 ID 号与之前的随机数字并列的 URL。

的意思是:第一次,当我点击链接时,我访问 URL mypage.com/#m=Profile&user_id= 加上随机数(例如 4542),但在第二次尝试时,我访问 URL mypage.com/#m=Profile&user_id=4542 加上另一个随机数。

为了避免在再次单击以获取正确链接之前刷新,我该怎么办?

提前感谢,对不起我的英语不好

或者

,你可以只做:

<a target="_blank"
    href="http://www.mypage.com/#m=Profile&user_id="
    onclick="this.href='#m=Profile&user_id='+(Math.floor(Math.random()*(75800000-59438709))+59438709)">Open a random profile. Click here!</a>

这将创建指向仅哈希部分的链接,并始终附加正确的 ID。

好吧,你有/#attr1&attr2。

但是在拆分方法中,您在"?尝试使用

<a target="_blank" href="http://www.mypage.com/#m=Profile&user_id=" onclick="this.href=this.href.split('#')[0]+(Math.floor(Math.random()*(75800000-59438709))+59438709)">Open a random profile. Click here!</a>

以上将为您提供:http://www.mypage.com/XXXXX 其中XXXXX是随机数。

对于"http://www.mypage.com/#m=Profile&user_id=XXXXX"格式,请使用以下命令:

<a target="_blank" href="http://www.mypage.com/#m=Profile&user_id=" onclick="this.href=this.href.split('#')[0]+'#m=Profile&user_id='+(Math.floor(Math.random()*(75800000-59438709))+59438709)">Open a random profile. Click here!</a>

您可以在 & 使用

<a target="_blank" href="http://www.mypage.com/#m=Profile&user_id=" onclick="this.href=this.href.split('&')[0]+'&user_id='+(Math.floor(Math.random()*(75800000-59438709))+59438709)">Open a random profile. Click here!</a>