开发者

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

1) How to programatically (without writing the onclick="javascript:.." at开发者_JAVA百科tribute) attach JavaScript (jQuery) function to the link below?

2) The simplest way to toggle hide/unhide after clicking on the Statement link? First click should display the DIV (unhide), the second click should hide it and so forth.

<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:

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

You can initially hide the <div> in multiple ways, CSS:

#taxStatement { display: none; }

Or give it a class, e.g. class="toggleDiv" and hide them all the same way:

.toggleDiv { display: none; }

Or also in your document.ready, via script:

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

You can give it a try/experiment here.


For Question 1 and 2, you'll want to use 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>.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜