2013-03-08 61 views
1

我的要求很简单,它必须检查变量并相应地显示/隐藏类。它位于sharepoint发布页面上。 使用以下代码段不起作用。Java脚本显示和隐藏

if (source = 'show') 
{ 
$('.classshide').hide(); 
} 
else 
{ 
$('.classsshow').hide(); 
} 

它的工作原理,只有当源变量是节目,它应该工作的otherway过,当它不等于显示或等于隐藏,请隐藏classshow。

+1

你需要改变'如果(来源=“秀”)''来,如果(来源==“秀”)' – jonhopkins 2013-03-08 18:17:24

+0

甚至没有在第一种情况下工作,如果我使用“==”到位'='。 – svs 2013-03-08 18:20:21

+0

你确定'source'是正确的值吗? – jonhopkins 2013-03-08 18:28:46

回答

2

您的平等测试是错误的。

if (source = 'show') 

应该

if (source == 'show') 

,也可能是

if (source === 'show') //if source is a string and you don't want type coercion 
0

请使用严格比较===。速度更快,因为在比较变量的value时,不需要转换type

编辑:

// get what the current state of hide/show is 
var source = $('.classhide').length === 0 ? 'show' : 'hide'; 

if (source === 'show') { 
    $('.classshide').hide(); 
} else { 
    $('.classsshow').hide(); 
} 
+0

不工作。现在,它甚至不适用于第一种情况。什么都没发生。 – svs 2013-03-08 18:27:54

+0

@svs然后我有一种感觉,当它用于比较时,'source'没有用实际值定义。 – sweetamylase 2013-03-08 18:31:23

0

您需要使用的平等(==)或全等(===)运算符来source变量 “秀” 在你的if语句比较。因为你提到需要显示以及隐藏类,我猜你想要交替显示哪些类,所以我相应地调整了其余的代码。

if (source === 'show') 
{ 
    $('.classshide').hide(); 
    $('.classsshow').show(); 
} 
else if (source === 'hide') 
{ 
    $('.classsshow').hide(); 
    $('.classshide').show(); 
} 
else // for some reason source is neither 'show' or 'hide' 
{ //default to the logic for if it is 'hide' 
    $('.classsshow').hide(); 
    $('.classshide').show(); 
} 
+0

出于某种原因,==或===不适合我。它至少检查第一个条件,如果我只使用=,否则失败。 – svs 2013-03-08 18:32:58

+0

你是什么意思,它不工作?你是否在if块之前设置变量,并且将它设置为正确的值? – jonhopkins 2013-03-08 18:35:20

+0

该变量正在页面中定义,我只是将其拉入我的脚本来检查是否阻塞。 – svs 2013-03-08 18:39:26