【问题标题】:Html, A tag using onclick functionatity for redirection [closed]Html,使用 onclick 功能进行重定向的标签 [关闭]
【发布时间】:2020-09-01 11:52:21
【问题描述】:
<a href='#' onclick='returnUrl = /url=(https?:\/\/.+)/.exec(location); if(returnUrl)location.href = returnUrl[1];else location.href = "/"'>Back to Blog</a>

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

【问题讨论】:

  • 这是一个很好的机会,可以将您的代码移动到一个函数中,并将每个操作拆分到自己的行中。然后使用浏览器的调试工具在代码执行时单步执行代码并检查每个操作的结果。当你这样做时,哪个操作不清楚?哪个操作产生了您意想不到的结果?
  • 我不懂html..你能解释一下onclick里面写的代码的工作原理吗?
  • (1) 您询问的具体代码是 JavaScript,而不是 HTML。 (2) 如果您不了解 HTML 或 JavaScript,那么您的第一步就是寻找一些关于这些技术的介绍性教程并开始学习。 Stack Overflow 可以帮助您解决代码中的特定问题,但我们不提供自定义辅导服务来教您这些技术。要了解有关此社区的更多信息以及我们如何为您提供帮助,请从 tour 开始并阅读 How to Ask 及其链接资源。
  • 我在过去的 4 个小时里一直在试图分解这段代码的工作。我知道点击它重定向到主页的链接和 exec 函数用于识别位置参数内的模式.但是我在我正在查看的网站的任何地方都找不到 returnUrl 参数。我也没有找到为什么 url http 的东西放在“/ /”之间。
  • 在您显示的代码中 returnUrl 被称为“变量”。变量用于在代码中存储值。由于它有一个隐式声明,默认情况下它是window 对象的一个​​属性。正斜杠之间的语法称为“正则表达式”。

标签: html tags


【解决方案1】:

在这个例子中:

  1. 您尝试将正则表达式 url=(https?:\/\/.+) 应用于当前位置,afaik “位置”无法返回以“url =”开头的内容,但我可能会出错。
  2. 您在 returnUrl var 中插入的 regex.exec 答案(它是数组)
  3. 如果给定数组中有一些条目,则在 location.href 中插入第二个条目(为什么是第二个?:Why capturing group results in double matches regex
  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 '/'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2021-07-01
    • 2019-07-27
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多