简体   繁体   English

如何切换/折叠javascript元素(默认情况下,我想折叠html)

[英]How do I toggle/collapse a javascript element (I want to collapse the html by default)

Hi I need help with my code to make the below html collapse because it does not collapse currently 嗨,我需要我的代码帮助,以使下面的html折叠,因为它当前不折叠

This is the javascript function code 这是javascript函数代码

function(event, ui) {
    html='';
    var show = "Yes";
    html += "<h5 id='collapsible'>"+ show +"</h5>";
};

$('#history').html(html);

Here is the html text code to show the Yes on the html page 这是在html页面上显示Yes的html文本代码

<div id="history"></div>

Please help me Toggle/Collapse the <div id="history"></div> 请帮助我切换/折叠<div id="history"></div>

如果您已经在使用jQuery,则只需使用toggle()

$("#history").toggle();

You can use javascript method for this: 您可以为此使用javascript方法:

function toggle() {
    var target = document.getElementById("history");
    if(target.style.display == 'block'){
        target.style.display = 'none';
    }
    else {
        target.style.display = 'block';
    }

To collapse the HTML by default, set the attribute: 要默认折叠HTML,请设置属性:

<div id="history" style="display:none;"></div>

jQuery Version : jQuery版本

http://www.codepen.io/anon/pen/xBdkl http://www.codepen.io/anon/pen/xBdkl

<div id="temp" onClick="javascript:func()">Show/Hide</div>
<p/>
<div id="history"></div>
<script>
var html='';
 var show = "Yes";
 html += "<h5 id='collapsible'>"+ show +"</h5>";
  $('#history').html(html);

var func = function(){
  if($("#history").is(":visible")){
      $('#history').hide();
  }else{
  $('#history').show();
 }
}
</script>

Javascript: 使用Javascript:

$('#collapseHistory').on('click', function(){
      $("#history").toggle();
});

HTML: HTML:

<div id="history" style="display: none;"></div>
<div id="collapseHistory">Show/Hide</div>

This should work 这应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM