簡體   English   中英

如何通過單擊鏈接以編程方式顯示和隱藏DIV?

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

1)如何以編程方式(無需編寫onclick =“ javascript:..”屬性)將JavaScript(jQuery)函數附加到下面的鏈接?

2)單擊“語句”鏈接后切換隱藏/取消隱藏的最簡單方法是? 第一次單擊應顯示DIV(取消隱藏),第二次單擊應將其隱藏,依此類推。

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

您可以給鏈接一個類,例如:

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

然后在附加腳本document.ready.click().toggle()的元素,就像這樣:

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

您可以通過多種方式來初始隱藏<div> CSS:

#taxStatement { display: none; }

或者給它一個類,例如class="toggleDiv"並用相同的方式隱藏它們:

.toggleDiv { display: none; }

或者也可以通過腳本在document.ready

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

您可以在此處進行嘗試/實驗

對於問題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