Java脚本显示和隐藏

Java script to show and hide

本文关键字:隐藏 显示 脚本 Java      更新时间:2023-09-26

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

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

它只在源变量为show时起作用,否则也应该起作用,当它不等于show或等于hide时,请隐藏类show。

你的相等性测试是错误的。

if ( source = 'show')
应该

if ( source == 'show')

或者

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

您需要使用相等(==)或严格相等(===)运算符来比较source变量与if语句中的"show"。因为您提到需要显示和隐藏类,我猜您想要交替显示哪些类,所以我相应地调整了其余的代码。

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();
}

请使用严格比较===。它更快,因为它在比较变量的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();
}