【问题标题】:jQuery if Cookie Value does not exist of multiple IndexOf'sjQuery 如果多个 IndexOf 的 Cookie 值不存在
【发布时间】:2011-06-16 22:57:35
【问题描述】:

我有一个用 jQuery 创建的名为“testCookie”的 cookie。我想检查这些值是否不存在,如果它们不存在(或等于或小于-1)我想做某事,下面的代码目前什么都不做,它假设代码是'甚至没有,并且在 if 语句之后加载所有内容,无论 cookie 值如何,有什么想法吗?

if ($.cookie('testCookie').indexOf('shopping','pricegrabber','nextag','shopzilla')<=-1) {

【问题讨论】:

    标签: jquery arrays cookies indexof


    【解决方案1】:

    indexOf 函数一次只能接受一个字符串。为此,您需要在 if 语句中包含多个子句,并与 &amp;&amp; 一起加入:

    if(cookieValue.indexOf('shopping') == -1 &amp;&amp; cookieValue.indexOf('pricegrabber') == -1)

    您可以将所有条件添加到该if 语句中。 &amp;&amp; 表示“如果这个和这个”等等。

    【讨论】:

      【解决方案2】:

      indexOf()的语法是这样的:

      ['a', 'b', 'c', 'd'].indexOf('b'); // returns 1
      

      你可以使用jQuery的.inArray()方法:

      $.inArray('b', ['a','b','c','d']); // returns 1
      

      如果$.cookie('testCookie') 返回字符串,你可以这样检查:

      if (['grabber','nextag','shopzilla'].indexOf($.cookie('testCookie')) == -1)  {
          // your code
      }
      

      if ($.inArray($.cookie('testCookie', ['grabber','nextag','shopzilla']) == -1) {
          // your code
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-01
        • 2010-11-13
        • 1970-01-01
        • 2011-09-15
        • 2017-09-19
        相关资源
        最近更新 更多