当我单击任何按钮时,唯一隐藏或取消隐藏的文本是第一个答案。
我希望按钮能够处理本地答案。就像问题旁边的按钮应该只对答案1起作用,答案2旁边的按钮应该只隐藏或取消隐藏问题2。我宁愿不对每个问题使用id的get元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Book Title</title>
<script>
function showFunction() {
var x = document.getElementsByClassName("answer")[0].style.color = 'black'
}
function hideFunction() {
var x = document.getElementsByClassName("answer")[0].style.color = 'white'
}
</script>
<style>
</style>
</head>
<body>
<h3> Flashcards </h3>
<p class="question">
This is the First Question
</p>
<div class="answer">
<p>
This is the First Answer
</p>
</div>
<div>
<label>Check Answer:</label>
<button onclick="showFunction()">Show Answer</button>
<button onclick="hideFunction()">Hide Answer</button>
</div>
<p class="question">
This is the Second Question
</p>
<p class="answer" >
This is the Second Answer
</p>
<br />
<div>
<label>Check Answer:</label>
<button onclick="showFunction()">Show Answer</button>
<button onclick="hideFunction()">Hide Answer</button>
</div>
<p class="question">
This is the Thrird Question
</p>
<p class="answer">
This is the Third Answer
</p>
<br />
<div>
<label>Check Answer:</label>
<button onclick="showFunction()">Show Answer</button>
<button onclick="hideFunction()">Hide Answer</button>
</div>
</body>
</html>
最佳答案
希望对您有帮助
function showFunction(val) {
var x = document.getElementsByClassName("answer"+val)[0].style.color = 'black'
}
function hideFunction(val) {
var x = document.getElementsByClassName("answer"+val)[0].style.color = 'white'
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Book Title</title>
<style>
</style>
</head>
<body>
<h3> Flashcards </h3>
<p class="question">
This is the First Question
</p>
<div class="answer1">
<p>
This is the First Answer
</p>
</div>
<div>
<label>Check Answer:</label>
<button onclick="showFunction(1)">Show Answer</button>
<button onclick="hideFunction(1)">Hide Answer</button>
</div>
<p class="question">
This is the Second Question
</p>
<p class="answer2" >
This is the Second Answer
</p>
<br />
<div>
<label>Check Answer:</label>
<button onclick="showFunction(2)">Show Answer</button>
<button onclick="hideFunction(2)">Hide Answer</button>
</div>
<p class="question">
This is the Thrird Question
</p>
<p class="answer3">
This is the Third Answer
</p>
<br />
<div>
<label>Check Answer:</label>
<button onclick="showFunction(3)">Show Answer</button>
<button onclick="hideFunction(3)">Hide Answer</button>
</div>
</body>
</html>