最近我一直在研究一点点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>
有效!为什么会那样?因为我会在网站上有很多桌子和其他需要隐藏和显示的东西,我不想为每个人创建一个新功能..:/
请帮帮我!
谢谢!
答案 0 :(得分:2)
非常简单使用 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>
干杯,别忘了投票给我答案 :)
答案 1 :(得分:1)
如果您正在传递元素引用,请将其用作选择器:
function toggleReport(table){
$(table).toggle();
}
注意我正在使用.toggle()
,它将完全按照您尝试手动执行的操作。如果要记录新状态,可以在回调中执行此操作:
function toggleReport( table ) {
$( table ).toggle('fast', function(){
console.log( "Element is visible? " + $(this).is(":visible") );
});
}
注意,如果您传入元素的ID,则需要修改选择器:
$( "#" + table ).toggle();
答案 2 :(得分:1)
答案 3 :(得分:0)
您可以使用toggle功能来实现此目标....
$(selector).toggle();
答案 4 :(得分:0)
演示 http://jsfiddle.net/uW3cN/2/
带参数传递的演示 http://jsfiddle.net/uW3cN/3/
良好的阅读API切换:http://api.jquery.com/toggle/
<强>码强>
function toggleReport(){
//removed the argument
$('#table_1').toggle();
}
其他示例其他html位于http://jsfiddle.net/uW3cN/3/
function toggleReport(tableid){
//removed the argument
$('#'+tableid).toggle();
}
答案 5 :(得分:0)
您在原始函数中犯的错误是您实际上没有使用传递给函数的参数。您选择了"#table"
,它只是在页面上选择一个ID为“table”的元素。它根本没有引用你的变量。
如果您打算将ID传递到选择器,则应写入jQuery("#" + table)
。如果table是对DOM元素的引用,那么您将编写jQuery(table)
(没有引号且没有井号)。