【问题标题】:Javascript IF used with ORJavascript IF 与 OR 一起使用
【发布时间】:2012-09-25 21:00:08
【问题描述】:

我确信这很容易,我也看到过类似的问题,但没有人能帮助我弄清楚为什么这不起作用。没有人能告诉我为什么当currentPage 设置为faqcontact 时这不会捕获吗?

<script type="text/javascript">
                function init() {
                document.getElementById('searchSubmit').onclick=function(){
                        var uriArgs = window.location.search;
                        var currentPage = uriArgs.match(/page=?(\w*)/);
                        if ( (currentPage == null) || (currentPage == 'faq') || (currentPage == 'contact') ) {
                                currentPage = "index";
                                document.getElementById('searchHidden').value = currentPage;
                        }
                        else {
                                document.getElementById('searchHidden').value = currentPage[1];
                        }
                }
                }
                window.onload=init;
        </script>

我设置了一个弹出警报,这样我就可以看到它是否被正确设置为faqcontact,所以我不确定为什么if 语句没有捕捉到这一点。

提前致谢!

【问题讨论】:

    标签: javascript string if-statement or-operator


    【解决方案1】:

    如果匹配,String.match 将返回数组索引 1 处的捕获组。示例:

    > 'page=sdfsfsdf'.match(/page=?(\w*)/)
    ["page=sdfsfsdf", "sdfsfsdf"]
    

    所以您需要查看match 返回的数组的内部(假设它不是null)。

    if (currentPage == null || currentPage[1] == 'faq' || currentPage[1] == 'contact') {
        /* ... */       
    }
    

    【讨论】:

    • omg 我不知道为什么这总是发生在我身上,但我只是在发布这个问题后才意识到这一点。感谢您的帮助。现在可以了。
    【解决方案2】:

    您的问题不在于if-statement,而是match method 的结果:它返回匹配和匹配组的数组 - 您想与第一个匹配组进行比较。

    var match = window.location.search = uriArgs.match(/page=?(\w*)/),
        currentPage = false;
    if (match != null)
        currentPage = match[1];
    
    if ( !currentPage || currentPage=='faq' || currentPage=='contact' ) {
        // do something
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多