仅当页面 url 包含特定字词时才显示文本
Show text only if page url contain specific word
仅当 URL 包含特定词时,我才需要在一页上显示一些文本。我尝试了几个在 Whosebug 上找到的示例,但似乎没有任何效果。
所以我需要在 URL - "/index.php?option=com_registration&task=register"
上显示文字
我尝试编写代码来识别 URL 中的单词 "register",但它不起作用。文本在所有页面上都可见。
编辑:我要显示的文字是 "Creating account will automatically put you on our bi-monthly newsletter email list. Please note: you can unsubscribe at any time."
并且它应该位于页面上每个内容之前。
您可以使用 URL API 解析浏览器的位置 URL,然后搜索 task
参数的值。如果匹配 register
,则执行显示文本的逻辑。
var url = new URL(window.location.href);
if (url.searchParams.task === 'register') {
// perform logic to show the text
}
请注意 URL API 在 Internet Explorer 中不可用。这种情况需要手动解析URL参数,或者使用第三方库,如URI.js.
你的 URL 是 - "/index.php?option=com_registration&task=register"
如果您使用 php
<?php
$check = $_GET['task'];
if(isset($check)){
#do something...
}
?>
要点是从 url 获取查询并检查它是否已设置,您正在通过这种方式使用 GET 方法执行此操作,因此您将使用 $_GET['parameterName']、变量获取它$check 将具有参数赋值
的值
我真的很喜欢@31piy 的回答,但是如果你必须支持 Internet Explorer 并且不想添加整个库只是为了简单的 URL 匹配,你总是可以使用好的旧正则表达式甚至indexOf
.
例如,您可以只对 "register" 或 "task=register".
使用正则表达式
如果您想进行简单比较(例如包含 task=register
),那么我会选择字符串比较:
if (window.location.href.indexOf('task=register') !== -1) {
// show text here
}
如果您想更灵活地进行匹配,您应该使用正则表达式:
var regex = /task=register/;
if (regex.test(window.location.href)) {
// show text here
}
有关正则表达式的更多信息,我强烈建议使用解释工具,例如 this one。
仅当 URL 包含特定词时,我才需要在一页上显示一些文本。我尝试了几个在 Whosebug 上找到的示例,但似乎没有任何效果。
所以我需要在 URL - "/index.php?option=com_registration&task=register"
上显示文字我尝试编写代码来识别 URL 中的单词 "register",但它不起作用。文本在所有页面上都可见。
编辑:我要显示的文字是 "Creating account will automatically put you on our bi-monthly newsletter email list. Please note: you can unsubscribe at any time."
并且它应该位于页面上每个内容之前。
您可以使用 URL API 解析浏览器的位置 URL,然后搜索 task
参数的值。如果匹配 register
,则执行显示文本的逻辑。
var url = new URL(window.location.href);
if (url.searchParams.task === 'register') {
// perform logic to show the text
}
请注意 URL API 在 Internet Explorer 中不可用。这种情况需要手动解析URL参数,或者使用第三方库,如URI.js.
你的 URL 是 - "/index.php?option=com_registration&task=register" 如果您使用 php
<?php
$check = $_GET['task'];
if(isset($check)){
#do something...
}
?>
要点是从 url 获取查询并检查它是否已设置,您正在通过这种方式使用 GET 方法执行此操作,因此您将使用 $_GET['parameterName']、变量获取它$check 将具有参数赋值
的值我真的很喜欢@31piy 的回答,但是如果你必须支持 Internet Explorer 并且不想添加整个库只是为了简单的 URL 匹配,你总是可以使用好的旧正则表达式甚至indexOf
.
例如,您可以只对 "register" 或 "task=register".
使用正则表达式如果您想进行简单比较(例如包含 task=register
),那么我会选择字符串比较:
if (window.location.href.indexOf('task=register') !== -1) {
// show text here
}
如果您想更灵活地进行匹配,您应该使用正则表达式:
var regex = /task=register/;
if (regex.test(window.location.href)) {
// show text here
}
有关正则表达式的更多信息,我强烈建议使用解释工具,例如 this one。