JS-这里有什么区别? [英] JS - What is the difference here?

查看:60
本文介绍了JS-这里有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS的新手,知道以下两个if语句条件之间的区别是非常有用的.

I'm a newbie to JS and it would be extremely useful to know what the differenece is between the following two if statement conditions...

第一个条件(实际上不起作用):

First condition (not actually working):

if ( window.location.pathname == '/#register' ) {

// Code

}

第二个条件:

if (document.URL.indexOf("#register") >= 0) {

// Code...

}

仅供参考,这将帮助我解决我在此处

FYI, this would help me solve a bug I'm experiencing here

推荐答案

第一个检查是否完全匹配.而且它是在不包含哈希的路径名上完成的,因此它可能无法满足您的要求.

The first checks for an exact match. And it does it on the pathname, which doesn't include the hash, so it probably doesn't do what you want.

第二个检查字符串是否包含"#register",因此完整路径可能更大,例如/#register_or_not/some/other/path#register

The second one checks the string contains "#register", so the full path could be bigger, like /#register_or_not or /some/other/path#register

也许最好的选择是对URL进行正则表达式模式匹配,以确保其匹配的哈希仅注册",同时允许URL的其余部分为:

Probably your best option would be to do a regex pattern match on the URL, to ensure that the hash it matches is ONLY 'register', while allowing the rest of the URL to be whatever:

if (document.URL.match(/.*#register$/)) {

这篇关于JS-这里有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆