开发者

What is wrong with my IF statement in javascript & jquery?

Basically I am hacking a foxycart setup I run and I need to basically hide a certain shipping option should a few things on the page exist...

1) that $value != United States (this is pulled dynamically from a text input but for purposes of showing you I've made it a static variable here

2) the number '.fc_cart_item' occurs is only once

3) the text in '.开发者_运维问答fc_cart_item_quantity' is only 1

and

4) the text in #fc_cart_table contains either Xyz or Zyx

Here is my statement that kinda works...

 var value = 'Australia';

if(    
    (    $value != 'United States'    &&    $('.fc_cart_item').size() < 2    &&    $('.fc_cart_item_quantity').text() < 2    )    &&    
    (    $('#fc_cart_table:contains(\'Zyx\')')    ||    $('#fc_cart_table:contains(\'Xyz\')')    )    
)

    {

       // do stuff

     }

Now this was working (whatever I put in // do stuff would occur) as I expect it when I had Xyz or Zyx in the cart... but then it was still doing stuff even when it was something other than Xyz or Zyx.

I'm coming from a PHP background so I don't know if I'm doing my if statement correctly here.


The if statement in your example will always return true because of the fact that the :contains selector does not return a boolean value that can be used safely for an if statement. Try this instead:

value = "Australia";

if( ( value != "United States" &&  $(".fc_cart_item").size() < 2 &&
   $(".fc_cart_item_quantity").text() < 2   ) &&
   ( $("#fc_cart_table").is(":contains('Zyx')") ||
   $("#fc_cart_table").is(":contains('Xyz')")    ) 
{

   // do stuff
}

BTW, your can tell that you're from a PHP background with your $value syntax... :)


It's "doing stuff" when these conditions are met:


$value != 'United States'    &&    $('.fc_cart_item').size() < 2    &&    $('.fc_cart_item_quantity').text() < 2    )

even if there is no Zyx or Xyz in the cart.


Try the following. Notice that variables do not get accessed by $value but by value. You should also not check for $('#fc_cart_table:contains(\'Zyx\')') - the result is an empty array which is boolean evaluated as true. Rather use either $('#fc_cart_table:contains(\'Zyx\')').size() or as used below:

var value = 'Australia';

if(    
    (    value != 'United States'    &&    $('.fc_cart_item').size() < 2    &&    parseInt($('.fc_cart_item_quantity').text()) < 2    )    &&    
    (    $('#fc_cart_table').text().indexOf('Zyx') > -1    ||    $('#fc_cart_table').text().indexOf('Xyz') > -1    )    
)
{
    // do stuff
}

/edit: I also added a parseInt() statement just for proper type usage's sake.


Remove the $ before value. And put parseInt() arround $('.fc_cart_item_quantity').text().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜