【问题标题】:How can I hide and show multiple divs and change button content at the same time?如何隐藏和显示多个 div 并同时更改按钮内容?
【发布时间】:2019-03-23 23:31:54
【问题描述】:

我正在尝试隐藏 div 并同时更改按钮的文本内容。

问题:我遇到的问题是 div 被隐藏但按钮的内容没有改变。

我将使用多个按钮来隐藏和显示多个图像和文本。

HTML

 <div class="hide-show-divs">
   <p>Some content in a div</p>
   <p>More content in a div</p>
 </div>

 <div class="hide-show-divs">
   <p>Some content in a div</p>
   <p>More content in a div</p>
 </div>

按钮

<div>
  <button class="hide-show-divs-btn" onclick="toggle()">Hide Divs</button>
</div>

JavaScript

function toggle() {
  var hideShowDivs = document.getElementsByClassName("hide-show-divs");
  for(var i = 0; i < hideShowDivs.length; i++){
    if (hideShowDivs[i].style.display === "none") {
      hideShowDivs[i].style.display = "block";
      changeBtnText();
    } else {
      hideShowDivs[i].style.display = "none";
    }
  }
}

function changeBtnText() {
  var hideShowImgBtn = document.getElementsByClassName("hide-show-divs-btn");
  for(var i = 0; i < hideShowImgBtn.length; i++)
    if(hideShowImgBtn[i].value =="Show divs") {
      hideShowImgBtn[i].value = "Hide divs";
    }else {
      hideShowImgBtn[i].value = "Show divs";
    }
  }

应该发生的是:

  1. 第一次单击按钮时 - 我希望隐藏 div 并将该按钮中的文本更改为“显示 div”。

  2. 我第二次单击按钮时 - 我希望显示 div 以及将该按钮中的文本更改回“隐藏 Divs”。

【问题讨论】:

  • 什么不起作用?你目前有什么行为?
  • @FutureCake 我遇到的问题是按钮的内容没有改变。

标签: javascript html


【解决方案1】:

你已经拥有了几乎大部分的功能,只是几个问题

  1. div 换行按钮中有引号,语法错误
  2. 在切换函数内部,您需要调用 changeBtnText 才能进行更改
  3. 按钮没有价值,所以如果你失败了,你可以使用innerText来代替它

function toggle() {
  var hideShowDivs = document.getElementsByClassName("hide-show-divs");
  changeBtnText(); // Invoking changeBtnText added
  for(var i = 0; i < hideShowDivs.length; i++){
    if (hideShowDivs[i].style.display === "none") {
      hideShowDivs[i].style.display = "block";
      changeBtnText();
    } else {
      hideShowDivs[i].style.display = "none";
    }
  }
}

function changeBtnText() {
  var hideShowImgBtn = document.getElementsByClassName("hide-show-divs-btn");
  for(var i = 0; i < hideShowImgBtn.length; i++)
    // Using innerText instead of value
    if(hideShowImgBtn[i].innerHTML =="Show divs") {
      hideShowImgBtn[i].innerHTML = "Hide divs";
    }else {
      hideShowImgBtn[i].innerHTML = "Show divs";
    }
  }

【讨论】:

  • 我应用了您的更改,但按钮的文本内容仍然没有改变
  • 谢谢。当我将 innerText 更改为 innerHTML 时,它会起作用。不知道为什么 innerText 对我不起作用。
【解决方案2】:

你可以使用 jQuery 女巫更容易:

第一步:添加jQuery

 <head>
 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
 </head>

现在是代码:

   $(".hide-show-divs-btn").click(function() {

      $( ".hide-show-divs" ).toggle();




      $(this).text() === 'Hide Divs'
      ? $(this).text('Show Divs')
      : $(this).text('Hide Divs')

     })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    相关资源
    最近更新 更多