如何使用按钮点击切换div的可见性 [英] How to Toggle a div's visibility by using a button click

查看:113
本文介绍了如何使用按钮点击切换div的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的javascript代码,我用来在点击按钮时显示 div



如何再次点击时将其隐藏?然后点击它, div 应该再次可见。

  ; script type =text / javascript> 
var _hidediv = null;
function showdiv(id){
if(_hidediv)
_hidediv();
var div = document.getElementById(id);
div.style.display ='block';
_hidediv = function(){div.style.display ='none'; };
}
< / script>


解决方案

如果你对一个jQuery解决方案感兴趣: / p>

这是HTML

 < a id =button href =#>显示/隐藏< / a> 
< div id =item> Item< / div>

这是jQuery脚本

  $(#button).click(function(){
$(#item).toggle();
});

您可以看到它在这里工作:



http://jsfiddle.net/BQUyT/



如果您不知道如何使用jQuery,你必须使用这一行来加载库:

 < script src =http ://code.jquery.com/jquery-1.10.1.min.js>< / script> 

然后使用此行开始:

 < script> 
$(function(){
//库在完成下载后触发的代码
});
< / script>

因此,对于这种情况,最终代码将是:

 < script> 
$(function(){
$(#button).click(function(){
$(#item).toggle();
} ;
});
< / script>

让我知道如果你需要什么



您可以在这里阅读更多关于jQuery的信息: http://jquery.com/


Below is my javascript code which i used to show a div when clicked on a button.

How can I hide it when clicked again? And then on clicking it, div should be visible again?

<script type="text/javascript">
var _hidediv = null;
function showdiv(id) {
    if(_hidediv)
        _hidediv();
    var div = document.getElementById(id);
    div.style.display = 'block';
    _hidediv = function () { div.style.display = 'none'; };
}
</script>

解决方案

In case you are interested in a jQuery soluton:

This is the HTML

<a id="button" href="#">Show/Hide</a>
<div id="item">Item</div>

This is the jQuery script

$( "#button" ).click(function() {
    $( "#item" ).toggle();
});

You can see it working here:

http://jsfiddle.net/BQUyT/

If you don't know how to use jQuery, you have to use this line to load the library:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

And then use this line to start:

<script>
$(function() {
    // code to fire once the library finishes downloading.
});
</script>

So for this case the final code would be this:

<script>
$(function() {
    $( "#button" ).click(function() {
        $( "#item" ).toggle();
    });
});
</script>

Let me know if you need anything else

You can read more about jQuery here: http://jquery.com/

这篇关于如何使用按钮点击切换div的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆