简体   繁体   English

如何通过单击链接以编程方式显示和隐藏DIV?

[英]How do I programmatically show and hide a DIV by clicking on a link?

1) How to programatically (without writing the onclick="javascript:.." attribute) attach JavaScript (jQuery) function to the link below? 1)如何以编程方式(无需编写onclick =“ javascript:..”属性)将JavaScript(jQuery)函数附加到下面的链接?

2) The simplest way to toggle hide/unhide after clicking on the Statement link? 2)单击“语句”链接后切换隐藏/取消隐藏的最简单方法是? First click should display the DIV (unhide), the second click should hide it and so forth. 第一次单击应显示DIV(取消隐藏),第二次单击应将其隐藏,依此类推。

<a>Statement</a>
<div id="taxStatement">insert select statement dropdownbox</div>

You can give the link a class, for example: 您可以给链接一个类,例如:

<a class="toggle" href="#">Statement</a>
<div id="taxStatement">insert select statement dropdownbox</div>

Then attach script on document.ready with .click() and .toggle() the element, like this: 然后在附加脚本document.ready.click().toggle()的元素,就像这样:

$(function() {
  $("a.toggle").click(function(e) {
    $(this).next().toggle();
    e.preventDefault();
  });
});

You can initially hide the <div> in multiple ways, CSS: 您可以通过多种方式来初始隐藏<div> CSS:

#taxStatement { display: none; }

Or give it a class, eg class="toggleDiv" and hide them all the same way: 或者给它一个类,例如class="toggleDiv"并用相同的方式隐藏它们:

.toggleDiv { display: none; }

Or also in your document.ready , via script: 或者也可以通过脚本在document.ready

$(".toggleDiv").hide();

You can give it a try/experiment here . 您可以在此处进行尝试/实验

For Question 1 and 2, you'll want to use toggle: 对于问题1和2,您需要使用toggle:

$('a').toggle(
function () {
  // Unhide Statement
  $('#taxStatement').show();
},
function () {
  $('#taxStatement').hide();
});
   var theDiv = $('#taxStatement');

   theDiv.hide();
// make the div hidden by default.

   theDiv.prev('a').click(function(){ theDiv.toggle(); });
// ^^^^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^^^^^^^^
// Attach the onclick                 hide & unhide.
//  assume the <a> is 
//  immediately before that <div>.
// It may be better to give an
//  id to that <a>.

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

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