亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

單擊同一 div 中的另一個元素后如何選擇特定元素

單擊同一 div 中的另一個元素后如何選擇特定元素

拉丁的傳說 2023-06-29 22:45:07
我有一個 h3 元素和 ap 元素,它們位于 div 元素內,如下所示:<div class="question">    <h3> <a href="#"> *a question* <img class="arrow" src="" alt="an-arrow-img"> </img> </a> </h3>    <p> *an answer* </p></div>我的 css 文件中有一個名為“show”的類,如下所示://shows the answer when I click the h3 element.show{   display: block;}在網站上,我試圖使問題答案看起來像這樣:顯示-隱藏 p 元素當我單擊問題(h3 元素)時,我使用 javascript 來切換類“show”,但我切換了所有這些問題,并且不知道如何選擇我單擊的那個。到目前為止,我的 JavaScript 代碼是這樣的:$("h3").on("click", function(){   $("p").toggleClass("show");});是我的 HTML 結構錯誤,還是有辦法結合 $(this) 選擇器來僅顯示我單擊的問題的答案?
查看完整描述

2 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

var question = document.getElementsByClassName("question");

var i;


for (i = 0; i < question.length; i++) {

  question[i].addEventListener("click", function() {

    this.classList.toggle("active");

    var answer = this.nextElementSibling;

    if (answer.style.maxHeight) {

      answer.style.maxHeight = null;

    } else {

      answer.style.maxHeight = answer.scrollHeight + "px";

    } 

  });

}

.question {

  background-color: #2d6596;

  color: #f1f1f1;

  cursor: pointer;

  padding: 18px;

  width: 100%;

  border: 1px solid white;

  text-align: left;

  outline: none;

  font-size: 15px;

  transition: 0.4s;

}


.active, .question:hover {

  background-color: #1a364f;

}


.question:after {

  content: '\002B';

  color: #f1f1f1;

  font-weight: bold;

  float: right;

  margin-left: 5px;

}


.active:after {

  content: "\2212";

}


.answer {

  padding: 0 18px;

  background-color: #f2f2f2;

  max-height: 0;

  overflow: hidden;

  transition: max-height 0.2s ease-out;

}

<button class="question">The question</button>

<div class="answer">

  <p>The answer</p>

</div>


<button class="question">The question</button>

<div class="answer">

  <p>The answer</p>

</div>


<button class="question">The question</button>

<div class="answer">

  <p>The answer</p>

</div>


查看完整回答
反對 回復 2023-06-29
?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

使用 JQuery.next() 選擇 $this 的同級。


$("h3").on("click", function(){

   $(this).next("p").toggleClass("show");

});


查看完整回答
反對 回復 2023-06-29
  • 2 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號