简体   繁体   English

jQuery VAR在IF语句中的用法

[英]jQuery VAR in IF statement usage

I am sure that this will be a simple solution for someone well versed in jquery. 我相信对于精通jquery的人来说,这将是一个简单的解决方案。

I am wanting to pass the path name into the if statement so 我想将路径名传递给if语句,所以

http://address.com/catalog/product <= catalog then gets passed into the if statment. 然后将http://address.com/catalog/product <=目录传递到if语句中。

if (/\/catalog\//.test(window.location)) {
  jQuery('#name-div').hide();
}

so it hides a div if its a child of http://address.com/catalog 因此,如果div是http://address.com/catalog的子级,它将隐藏div

var url = location.pathname.split("/")[1];

if (/\/url\//.test(window.location)) {
  jQuery('#name-div').hide();
}

you can do it in many way like: 您可以通过多种方式来做到这一点,例如:

if( window.location.indexOf(url) !== -1 )

or

if( window.location.search( /url/ig ) )

or

if( window.location.match( /url/ig ).length > 0 )

In this examples you don't even need to use jQuery. 在此示例中,您甚至不需要使用jQuery。 It is just normal javascript. 这只是普通的javascript。

You basically have the answer to your own problem. 您基本上可以解决自己的问题。

$(function(){
    var url = window.location.href;

    if( /catalog/i.test(url) )
        $('#name-div').hide();
});

Unless you have other URLS with catalog in them, there's no reason to dissect the URL any further. 除非您有其他带有目录的URL,否则没有理由进一步剖析URL。 Just make sure you select your element after the DOM is ready as I did in my example. 就像我在示例中所做的那样,只需确保在DOM准备就绪后选择元素即可。

As I read your question, what you need is to create a RegExp object from a string since your want to pad with / characters: 当我读到您的问题时,您需要从字符串创建RegExp对象,因为您想使用/字符进行填充:

var url = location.pathname.split("/")[1],
    re = new RegExp('/' + url + '/'); // Create RegExp object from padded string

if (re.test(window.location)) {
    jQuery('#name-div').hide();
}

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

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