首页 > 解决方案 > Html,使用 onclick 功能进行重定向的标签

问题描述

<a href='#' onclick='returnUrl = /url=(https?:\/\/.+)/.exec(location); if(returnUrl)location.href = returnUrl[1];else location.href = "/"'>Back to Blog</a>

谁能详细解释一下上面的代码?

标签: htmltags

解决方案


在这个例子中:

  1. 您尝试将正则表达式url=(https?:\/\/.+)应用于当前位置,afaik“位置”无法返回以“url =”开头的内容,但我可能会出错。
  2. 您在 returnUrl var 中插入的 regex.exec 答案(它是数组)
  3. 如果给定数组中有一些条目,则在 location.href 中插入第二个条目(为什么是第二个?:为什么捕获组导致双重匹配正则表达式
  4. 如果给定数组中没有条目,则在 location.href 中插入“/”

将值插入“位置”变量相当于导航到插入的 url

来自 regex.com 的正则表达式解释

url= matches the characters url= literally (case sensitive)
1st Capturing Group (https?:\/\/.+)
http matches the characters http literally (case sensitive)
s?
matches the character s literally (case sensitive)
: matches the character : literally (case sensitive)
\/ matches the character / literally (case sensitive)
\/ matches the character / literally (case sensitive)
.+
matches any character (except for line terminators)

你的伪代码示例:

if there is matches for /url=(https?:\/\/.+)/ in location
then redirect to this match (in group)
else redirect to '/'

推荐阅读