当我单击显示消息的按钮时,这是我的代码,但是我无法通过再次单击按钮来隐藏此消息,我该如何解决。在html网页中,当我单击按钮时显示一个按钮,它显示一些消息,但是当我再次单击按钮时,我需要帮助,然后它隐藏了在网页中显示的消息。这是我的代码:-
//here is my code for button ..if i clicked on button then it show gameRules by one clicking but i want to hide this after again clicking in my html page
const gameRules = [{
Rule: "you want to touch this"
},
{
Rule: 'You are son of GOD'
},
{
Rule: 'You are real krackon'
}
]//here is gameRules show when button clicked
//here is code how above message show by clicking the button on html page
document.querySelector('.ram').addEventListener('click', function(e) {
var taki = e.target.value
for (var i = 0; i < gameRules.length; i++) {
const taki = document.createElement('h2')
taki.textContent = gameRules[i].Rule
document.querySelector('body').appendChild(taki)
}
})
<!DOCTYPE html>
<html>
<head></head> <!-- here is my html code for showing the button -->
<body>
<button class="ram"> click me</button> <!-- when i clicked on this button getting the messages but how can i hide this message by again clicking the button -->
</body>
</html>
答案 0 :(得分:0)
也许这样会实现您想要的?
//here is my code for button ..if i clicked on button then it show gameRules by one clicking but i want to hide this after again clicking in my html page
let messageShown = false;
const gameRules = [{
Rule: "you want to touch this"
},
{
Rule: 'You are son of GOD'
},
{
Rule: 'You are real krackon'
}
] //here is gameRules show when button clicked
// Create the elements when the page loads
for (var i = 0; i < gameRules.length; i++) {
const taki = document.createElement('h2');
taki.textContent = gameRules[i].Rule;
document.querySelector('#Message').appendChild(taki);
}
//here is code how above message show by clicking the button on html page
document.querySelector('.ram').addEventListener('click', function(e) {
// Toggle the display of the message
messageShown = !messageShown;
if (messageShown === true) {
document.getElementById('Message').style.display = 'block';
} else {
document.getElementById('Message').style.display = 'none';
}
})
#Message {
display: none;
}
<!DOCTYPE html>
<html>
<head></head>
<!-- here is my html code for showing the button -->
<body>
<button class="ram"> click me</button>
<!-- when i clicked on this button getting the messages but how can i hide this message by again clicking the button -->
<div id="Message">
</div>
</body>
</html>