为什么jquery中的代码不能工作

why the code in jquery doesn't work?

本文关键字:不能 工作 代码 jquery 为什么      更新时间:2023-09-26

url如下:http://example.com/download/

var pathname = window.location.pathname;
if(pathname=='download/'){
$("#subnav-content div:first").hide();
$("#subnav-content div:second").show();
}

为什么上面的代码在jquery不工作?当url是http://example.com/download/时。显示第二个div

ps*:此检查是否影响站点性能? *

你需要斜杠。

/下载/"

如果您希望查询字符串参数,您可以尝试使用正则表达式来匹配url的下载部分:以下匹配/download/.

if (window.location.pathname.match(/^'/download'//i))
关于jquery,没有:第二,你需要使用:eq(1)
var pathname = window.location.pathname;
if(pathname=='/download/'){
$("#subnav-content div:first").hide();
$("#subnav-content div:eq(1)").show();
}

对注释的回应

我把我的评论放在这里是因为在评论的格式是可怕的。下载匹配的正则表达式可以总结如下:

/ -正则表达式匹配语法的开始
^ -表示在屏幕最开始处开始匹配
'/ -表示匹配字符串'/',这是一个必须转义的特殊字符
download -匹配字符串'download'
'/ -同样表示匹配字符串'/'
/ -匹配语法结束
i -正则表达式选项,i表示忽略大小写

我不清楚你的另一张便条是要什么。

Second不是选择器。你想要的:

$("#subnav-content div:nth-child(2)").show();

尝试使用

$("#subnav-content div:eq(0)")
$("#subnav-content div:eq(1)")

此外,您需要将代码绑定到一个事件,该事件将在文档准备好时被触发(load,或onDOMReady,如果支持),否则div可能还不存在于内存中。

ps*:此检查是否影响站点性能?*

每一行代码都对站点性能有影响。虽然不一定是可见的