Javascript 隐藏/显示许多元素

标签 javascript html show-hide

在我的 HTML 中,我有问题和解决方案。我想用不同的按钮隐藏和显示每个问题的解决方案。

这是我的问题:我正在为每个解决方案按钮编写一个新函数。例如,如果我有 100 个问题,那么我需要编写 100 个不同的 Javascript 函数。

有没有更好的方法来做到这一点。我可以为每个解决方案按钮只编写一个函数吗?

非常感谢您。

这是我的 html:

<li>Question 1. What is x?</li>
<button class="btn btn-outline-success" 
onclick="myFunction()">Solution</button>
<div id="Solution">
<div class="highlight">
<pre>
X is apple
</pre>

<li>Question 2. What is y?</li>
<button class="btn btn-outline-success" 
onclick="myFunction1()">Solution</button>
<div id="Solution1">
<div class="highlight">
<pre>
Y is orange
</pre>

这是我的 Javascript:

document.getElementById( 'Solution' ).style.display = 'none';

function myFunction() {
    var x = document.getElementById('Solution');
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}

document.getElementById( 'Solution1' ).style.display = 'none';

function myFunction1() {
    var x = document.getElementById('Solution1');
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}

注意:我看到很多关于隐藏和显示的问题,但我无法解决我的问题。如果这是一个重复的问题,请警告我,我可以删除。

最佳答案

您可以通过传递一个参数来重用单个函数,该参数标识应显示/隐藏文档中的哪个元素:

document.getElementById( 'Solution' ).style.display = 'none';

// The function now expects to be passed the ID of the element
function myFunction(elementID) {
    var x = document.getElementById(elementID);
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}

现在,您可以重复调用该函数,每次只传递不同的元素 id:

 <li>Question 1. What is x?</li>
 <button class="btn btn-outline-success" onclick="myFunction('Solution')">Solution</button>
 <div id="Solution">
   <div class="highlight">
     <pre>X is apple</pre>
   </div>
 </div>

<li>Question 2. What is y?</li>
<button class="btn btn-outline-success" onclick="myFunction('Solution1')">Solution</button>
<div id="Solution1">
  <div class="highlight">
    <pre>Y is orange</pre>
  </div>
</div>

话虽如此,您应该尽可能避免使用内联 HTML 事件属性(onclickonmouseover 等)。有 many reasons 为什么。此外,您可以通过切换使用预先存在的 CSS 类来简化设置,而不是重复设置内联样式。另外,您的 HTML 语法无效。

这是您的代码经过清理、有效且现代的版本。您所要做的就是复制问题的 HTML 结构,现有的 JavaScript 将立即为它工作。每个问题甚至不再需要名称(“Solution1”、“Solution2”等)。

// Get all the buttons in a node list
var theButtons = document.querySelectorAll(".btn-outline-success");

// Turn node list into a JS Array
var buttonArray = Array.from(theButtons);

// Loop over the buttons and give each its click event handler
buttonArray.forEach(function(button){
  button.addEventListener("click", function(){ 
    // We will pass a reference to the current button to the function
    myFunction(this); 
  });
});

// The function now expects to be passed a reference to the button that was clicked
function myFunction(element) { 
  // Get a reference to div that follows the button and then search that div
  // for the first pre element inside of it:
  var answer = element.nextElementSibling.querySelector("pre");
  
  // All we need to do is toggle the visibility of that pre element
  answer.classList.toggle("hidden");
}
/* This class will simply be added or removed to show/hide elements */
/* All answers have this applied by default*/
.hidden {
  display:none;
}

li { margin-bottom:10px; }
<!--
    NOTES:
           1. The onclick has been removed (it is now handled in JavaScript) 
           2. The quesiton names ("Solution", "Solution1", etc.) are no longer needed
           3. Your HTML structure was invalid. Here is the proper way to make bulleted lists.
-->

<ul>
  <li>Question 1. What is x?
      <button class="btn btn-outline-success">Solution</button>
      <div>
        <div class="highlight">
          <pre class="hidden">X is apple</pre>
        </div>
      </div>
  </li>
    
  <li>Question 2. What is y?
      <button class="btn btn-outline-success">Solution</button>
      <div>
        <div class="highlight">
          <pre class="hidden">Y is orange</pre>
        </div>
      </div>
  </li>

  <li>Question 3. What is z?
      <button class="btn btn-outline-success">Solution</button>
      <div>
        <div class="highlight">
          <pre class="hidden">z is mango</pre>
        </div>
      </div>
  </li>
</ul>

关于Javascript 隐藏/显示许多元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46222147/

相关文章:

javascript - 为什么 Firebase 时间戳对象返回未定义?

javascript - 使用 document.getElementById ("demo").innerHTML 进行打印

javascript - AngularJS:无法检索 JSON 文件

javascript - CSS更改屏幕文本框的大小

javascript - 使用 jquery mobile 隐藏和显示 div

javascript - 根据选择下拉列表显示或隐藏多个字段 - jquery

javascript - 如何模拟回调函数接收到的数据(参数),以便可对于Jest地测试回调函数中的逻辑? (例如 fs.readFile)

html - 制作下拉菜单

html - 文本超出容器 div

javascript - 'checkbox' 到 'show div' 更简单的方法是什么?