javascript 在 html 中隐藏/显示链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8412265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:22:11  来源:igfitidea点击:

Hide/Show Links in html

javascriptjqueryhtml

提问by JaveDeveloper

I want to show 2 links - Show and Hide. When I click on Show, Show should be hidden and Hide should be visible and when I click on Hide, Hide should be hidden and Show should be visible. How can I achieve this in html?

我想显示 2 个链接 - Show 和 Hide。当我点击 Show 时,Show 应该是隐藏的,Hide 应该是可见的,当我点击 Hide 时,Hide 应该是隐藏的并且 Show 应该是可见的。我怎样才能在 html 中实现这一点?

回答by Billy Moon

with jquery in the head

头部有 jquery

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>

and an id for each button

和每个按钮的 id

<input type='button' id='show' value='Show' />
<input type='button' id='hide' value='Hide' />

you can do it something like this untested code...

你可以像这个未经测试的代码那样做......

<script type='text/javascript'>
    $(function(){
        $('#show').click(function(){
            $('#hide').hide()
        })
        $('#hide').click(function(){
            $('#show').hide()
        })
    })
</script>

回答by kubetz

Do you really only want to hide "hide" when "show" is clicked and vice versa? Because that is what you asked for, but it doesn't really sound as a "standard" (toggle) behaviour.

您真的只想在单击“显示”时隐藏“隐藏”,反之亦然?因为这就是您所要求的,但这听起来并不是“标准”(切换)行为。

But here it is:

但这里是:

See thissnippet.

看到这个片段。

HTML:

HTML:

<a href="#" id="show">SHOW</a>
<a href="#" id="hide">HIDE</a>

JS:

JS:

var showElem = document.getElementById("show");
var hideElem = document.getElementById("hide");

showElem.onclick = function() {
   hideElem.style.display = 'none';
}

hideElem .onclick = function() {
   showElem.style.display = 'none';
}

Instead of .style.display = 'none';you can use .style.visibility = 'hidden'which will still hide the link, but there will be empty space instead of it and it won't really completely dissapear (see thissnippet).

而不是.style.display = 'none';您可以使用.style.visibility = 'hidden'which 仍将隐藏链接,但会有空白空间而不是它,并且它不会真正完全消失(请参阅代码段)。

Update:Based on discussion in the comments section new simple example was created (see this) that have more "standard" behaviour. In case the page is expected to be heavy on effects or other javascript functionality (like Ajax) I would recommend to use 3rd party library like jQuery to simplify the implementation - see answer by Billy Moon.

更新:根据评论部分中的讨论,创建了具有更多“标准”行为的新简单示例(请参阅)。如果页面预计会影响效果或其他 javascript 功能(如 Ajax),我建议使用 jQuery 等 3rd 方库来简化实现 - 请参阅Billy Moon 的回答。