JavaScript JQuery 隐藏/显示功能

标签 javascript jquery

所以最近我一直在研究一些 js。

所以,基本上,我的问题是我需要隐藏参数中传递的任何内容,或者如果它已经隐藏则显示它。

这是我的代码:

<script type='text/javascript'>
<!--
function toggleReport(table){
//the table argument is the table's id
alert(table);                    //to check that the name of the table is right
if($('#table').is(':visible')){ //check if visible
    $('#table').hide();     //if so, hide it
    alert('hide');          //send a message that it is now being hidden
}else{                          //if already hidden
alert('show');                  //send a message that it is now being shown
$('#table').show();             //show the table
}

}
//-->
</script>

但是,它不起作用....它正在发送警报,一切都是正确的,但是,它不会隐藏或显示表格....

但是,如果我尝试这样做:

<script type='text/javascript'>
<!--
function toggleReport(){
//removed the argument
alert('table_1');
if($('#table_1').is(':visible')){
    $('#table_1').hide();
    alert('hide');
}else{
alert('show');
$('#table_1').show();
}

}
//-->
</script>

有效!为什么会这样?因为我将在网站上有很多表格和其他需要隐藏和显示的东西,我不想为每个表格创建一个新功能.. :/

请帮帮我!

谢谢!!

最佳答案

非常简单,使用toggle()代替show()/hide(),toggle()使隐藏的元素可见,可见的隐藏.

<script type='text/javascript'>;
function toggleReport(element_ID){
$("#"+element_ID).toggle();
}
</script>

如果您想对元素 ID 进行硬编码而不是使用以下脚本

<script type='text/javascript'>
function toggleReport(){
$("#table_1").toggle();
}
</script>

干杯,不要忘记投票赞成我的答案 :)

关于JavaScript JQuery 隐藏/显示功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748783/

相关文章:

javascript - ng-repeat 按特定顺序显示 html

javascript - 将函数作为参数传递给其他函数

javascript - 无法在 WebStorm 中列出 Grunt 任务错误

javascript - Mongoose.findOneAndUpdate() 没有创建新文档

jquery - 当我点击 div 之外的任意位置时,如何使 div 关闭?

jquery - 我无法让我的 jquery 代码工作?

jquery - 如何在 jquery 中将项目数组循环两个并放入另一个数组?

javascript - TypeError : Chartist.plugins.legend不是一个函数

javascript - TinyMCE 在加载 AJAX 的 DIV 中重新初始化后消失

javascript - jQuery/Bootstrap : dropdown-toggle is not setting the selected menu item as default selected item