简体   繁体   English

为什么jQuery中的代码不起作用?

[英]why the code in jquery doesn't work?

the url is as this: http://example.com/download/ 网址是这样的: http://example.com/download/ : http://example.com/download/

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

why the above code in jquery doesn't work? 为什么上面的代码在jQuery中不起作用? i want to when the url is http://example.com/download/ . 我想在网址为http://example.com/download/时使用 show the secong div. 显示第二分区

ps* :does this check affect the site performance? ps * :此检查是否会影响网站性能? * *

You need the leading slash. 您需要使用斜杠。

'/download/' '/下载/'

If you expect query string parameters you may try a regular expression to just match the download portion of the url: the following matches /download/. 如果您期望查询字符串参数,则可以尝试使用正则表达式来匹配url的下载部分:以下匹配/ download /。

if (window.location.pathname.match(/^\/download\//i))

Regarding the jquery, there is no :second, you need to use :eq(1) 关于jQuery,没有:second,您需要使用:eq(1)

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

Response to comments 对评论的回应

I'm putting my comment here because the formatting is horrible in the comments. 我在这里发表评论,因为评论中的格式太糟糕了。 The regular expression for matching download can be summed up as follows: 匹配下载的正则表达式可以总结如下:

/ - start of regular expression matching syntax / -正则表达式匹配语法的开始
^ - means start matching at the very start of the screen ^ -表示从屏幕最开始开始匹配
\\/ - means match the literal string '/', which is a special character which must be escaped \\/ -表示匹配文字字符串'/',这是必须转义的特殊字符
download - match the literal string 'download' download匹配文字字符串“ download”
\\/ - again means match the literal string '/' \\/ -再次表示匹配文字字符串'/'
/ - end of the matching syntax / -匹配语法的结尾
i - regular expression options, i means ignore case i -正则表达式选项,我的意思是忽略大小写

It was not clear to me what your other note was asking for. 我不清楚您的其他要求是什么。

Second is not a selector. 其次不是选择器。 You want: 你要:

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

Try using 尝试使用

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

Also, you need to bind the code to an Event that will get fired when the Document is ready( load , or onDOMReady where supported) otherwise the div s might not exist in memory yet. 另外,您需要将代码绑定到一个事件,该事件将在Document准备就绪时load (如果支持,请loadonDOMReady ),否则将在内存中不存在div

ps*:does this check affect the site performance?* ps *:此检查是否会影响网站性能?*

Every line of code has an effect on site performance. 每行代码都会影响站点性能。 Not necessarily a visible one although. 虽然不一定是可见的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM