javascript 按类别切换可见性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19459793/
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-27 15:39:45  来源:igfitidea点击:

Toggle Visibility By Class

javascript

提问by mike

Hi can anyone help me please.

嗨,任何人都可以帮助我。

How can i use Toggle Visibility by class instead of a id for example.

例如,我如何按类而不是 id 使用 Toggle Visibility。

The Button

按钮

<a href="javascript:void(0);" onclick="toggle_visibility('trailer');">Trailer</a>

Then this.

那么这个。

<div class="trailer" style="display:none">{include file="trailer.tpl"}</div>

So how can i modify this javascript to work with classes.

那么我如何修改这个 javascript 以使用类。

{literal}
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>                
{/literal}  

So what would javascript by for this please help.

那么 javascript 会为此提供什么帮助。

回答by Jonathan

Use getElementsByClassName

使用 getElementsByClassName

function toggle_visibility(className) {
    elements = document.getElementsByClassName(className);
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.display = elements[i].style.display == 'inline' ? 'none' : 'inline';
    }
}

回答by mplungjan

Inline:

排队:

<a href="#" 
 onclick="var div = document.querySelectorAll('trailer')[0]; 
 div.style.display=div.style.display=='none'?'block':'none';return false">Trailer</a>

jQuery:

jQuery:

$(function() {
  $("#link").on("click",function(e) {
    e.preventDefault();
    $(".trailer").toggle();
  });
});

Generic jQuery:

通用jQuery:

$(function() {
  $(".link").on("click",function(e) {
    e.preventDefault();
    $("."+this.id).toggle();
  });
});

using

使用

<a href=".." class="link" id="trailer">Toggle</a>

回答by Nicolás Straub

function toggle_visibility(className) {
    $('.' + className).toggle();
}

you should use jQuery to avoid browser compatibility issues.

您应该使用 jQuery 来避免浏览器兼容性问题。