[英]javascript toggle button to open and close a div
How can I get my toggle button to not only change names from view to hide but to also display a table that I have in a div tag? 如何获得切换按钮,不仅可以将名称从视图更改为隐藏,还可以显示div标签中包含的表?
I currently have the following for my script: 我的脚本当前具有以下内容:
<script type = "text/javascript">
function buttonToggle(where,pval,nval)
{
where.value = (where.value == pval) ? nval : pval;
}
</script>
and this is the code for the button: 这是按钮的代码:
<input type="button" name="button1" id="nextbt" value="View " onclick="buttonToggle(this,'View ','Hide ')">
Well if you can use jQuery it would be very easy: 好吧,如果您可以使用jQuery,那将非常简单:
$('#nextbt').click(function() {
if ($(this).attr('value') == 'show') {
$(this).attr('value', 'hide');
$('#myotherdiv').slideDown();
} else {
$(this).attr('value', 'show');
$('#myotherdiv').slideUp();
}
// or if you don't care about changing the button text, simply:
$('#myotherdiv').slideToggle();
});
More here: http://api.jquery.com/slideToggle/ 此处更多信息: http : //api.jquery.com/slideToggle/
Something like: 就像是:
function buttonToggle(where,pval,nval) {
var display = where.value === nval ? 'none' : 'block'; // or 'table'
document.getElementById('yourTableId').style.display = display;
where.value = (where.value == pval) ? nval : pval;
}
Or better: 或更好:
function buttonToggle(source, target, show_val, hide_val) {
var display = source.value === hide_val ? 'none' : 'block'; // or 'table'
target.style.display = display;
source.value = (source.value == show_val) ? hide_val : show_val;
}
and instead of adding your click handler inline, use JavaScript: 而不是内联添加您的点击处理程序,请使用JavaScript:
document.getElementById('nextbt').onclick = (function() {
var table = document.getElementById('yourTableId');
return function() {
toggleButton(this, table, 'View', 'Hide');
};
}());
use jQuery. 使用jQuery。 see demo http://jsfiddle.net/nBJXq/2/
参见演示http://jsfiddle.net/nBJXq/2/
Let's say you add the id
of the table you want to show/hide as the rel
attribute of the button: 假设您将要显示/隐藏的表的
id
添加为按钮的rel
属性:
<input type="button" name="button1" id="nextbt"
rel="myTable" value="View "
onclick="buttonToggle(this,'View ','Hide ')">
<table id="myTable">
<tr>
<td>myTable</td>
</tr>
</table>
Then you could add the following to your buttonToggle
function: 然后,您可以将以下内容添加到
buttonToggle
函数中:
function buttonToggle(where, pval, nval) {
var table = document.getElementById(where.attributes.rel.value);
where.value = (where.value == pval) ? nval : pval;
table.style.display = (table.style.display == 'block') ? 'none' : 'block';
}
You will want to change the div's style.visible
to visible
or hidden
, and/or set the style.display
to block
or none
. 您将需要将div的
style.visible
更改为visible
或hidden
,和/或将style.display
设置为block
或none
。
See: http://w3schools.com/css/css_display_visibility.asp 请参阅: http : //w3schools.com/css/css_display_visibility.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.