所以我必須創建這個程式,我需要在其中創建一個“人們還要求”功能(默認情況下這將隱藏答案,如果單擊問題,它將顯示該特定問題的答案),但是我不'不知道如何使用我自己的 Display() 和 Answer() 函式隱藏和顯示元素。我很難過,因為我對 JavaScript 還很陌生。
任何幫助將不勝感激!謝謝!
uj5u.com熱心網友回復:
display:none如果答案和問題是相關的,您可以在添加偵聽器以洗掉或添加具有屬性的類時遍歷它們。見片段。
const questions = document.querySelectorAll(".question");
const answers = document.querySelectorAll(".answer");
questions.forEach((question, index) => {
question.addEventListener("click", () => {
let answer = answers[index].classList;
answer.contains("hidden") ? answer.remove("hidden") : answer.add("hidden");
});
});
.hidden {
display:none ;
}
<main>
<h1>People also ask</h1>
<ul id="questions">
<li>
<div class="question">
How do I enable JavaScript Chrome?
</div>
<div class="answer hidden">
<p><strong>If you'd like to turn JavaScript off or on for all sites:</strong></p>
<ol>
<li>Click the Chrome menu in the top right-hand corner of your browser.</li>
<li>Select Settings.</li>
<li>Click Show advanced settings.</li>
<li>Under the "Privacy" section, click the Content settings button.</li>
</ol>
</div>
<div class="question">
What do you use JavaScript for?
</div>
<div class="answer hidden">
<p><strong>Webpages</strong></p>
<ol>
<li>JavaScript is commonly used for creating web pages.
It allows us to add dynamic behavior to the webpage and add special effects to the webpage.
On websites, it is mainly used for validation purposes.
JavaScript helps us to execute complex actions and also enables the interaction of websites with visitors.
</ol>
</div>
<div class="question">
What does JavaScript do?
</div>
<div class="answer hidden">
<p><strong>JavaScript</strong></p>
<ol>
<li>JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else.
(Okay, not everything, but it is amazing what you can achieve with a few lines of JavaScript code.)</li>
</ol>
</div>
<div class="question">
Is it useful to learn JavaScript?
</div>
<div class="answer hidden">
<p><strong>Why learn JavaScript?</strong></p>
<ol>
<li>The most obvious reason for learning JavaScript is if you have hopes of becoming a web developer.
Even if you haven't got your heart set on a tech career,
being proficient in this language will enable you to build websites from scratch—a pretty useful skill to have in today's job market!
</ol>
</div>
</li>
</main>
uj5u.com熱心網友回復:
正如您正確指出的那樣,顯示/隱藏元素的最佳方法是修改 CSS 屬性display。
現在,在您的情況下,我將添加一個.hidden您添加到要隱藏的元素的類。然后要顯示它們,您只需從相應元素中洗掉該類。
.hidden {
display: none;
}
function toggleElementById(elementId) {
var element = document.getElementById(elementId);
element.classList.toggle("hidden");
}
如果為每個答案添加一個 ID,并為問題添加一個目標屬性,您可以輕松地從問題元素中獲取目標 ID。
<div class="question" data-target="answer1">
What does JavaScript do?
</div>
<div class="answer" id="answer1">
<!-- ... -->
</div>
function toggleAnswer(e) {
var target = e.target.getAttribute("data-target");
toggleElementById(target);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411850.html
標籤:
上一篇:如何定義每個單元測驗的類實體?
