gpt4 book ai didi

javascript - 如果 URL 包含任何内容,则触发 Javascript 函数

转载 作者:行者123 更新时间:2023-11-28 13:45:46 25 4
gpt4 key购买 nike

基本上,如果 URL/window.location 绝对包含任何变量(当然是过去的domain.com/),我希望 javascript 执行某些操作。

目前,我有以下 jQuery 代码,仅当 window.location 包含确切的措辞“#hash”时才执行,但如前所述,我想扩展所有变量的功能。

编辑:抱歉,为了澄清一下,我所说的变量是指以下示例之一:

  • domain.com/#hash
  • domain.com/#hash2
  • domain.com/子/文件夹
  • domain.com/textwithoutahash

此外,如果有人知道如何用基本的 Javascript 实现这一点,而不需要 jQuery 库,那将是一个额外的好处!

$(function() {
if ( window.location.href.indexOf('#hash') > -1 ) {
myfunctionhere;
}
});

最佳答案

请参阅最后的更新以了解您的说明

将脚本放在页面末尾、结束之前 </body> ,并且:

如果“变量”指的是文档片段标识符(“哈希”),那么:

<script>
if (location.hash) {
callYourFunction();
}
</script>

如果“变量”指的是查询字符串,那么

<script>
if (location.search) {
callYourFunction();
}
</script>

如果“变量”指的是资源名称,例如,不是 http://domain.com但是http://domain.com/page ,那么:

<script>
if (location.pathname && location.pathname !== "/") {
callYourFunction();
}
</script>

有关位置对象的更多信息 on MDN .

<小时/>

请澄清:

Edit: Sorry, to clarify, by variable I mean any one of the following examples:

这些例子归结为 hashpathname或两者兼而有之,所以:

<script>
if ((location.pathname && location.pathname !== "/") || location.hash) {
    callYourFunction();
}
</script>

...当然,如果您也想处理 http://domain.com?foo=bar ,然后添加 search还有:

<script>
if ((location.pathname && location.pathname !== "/") ||
location.search ||
location.hash) {

    callYourFunction();
}
</script>

关于javascript - 如果 URL 包含任何内容,则触发 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14517292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com