切换一个按钮控制多个div的显示与隐藏。

huangapple go评论67阅读模式
英文:

Toggle show hide for multiple divs with one button

问题

以下是您要翻译的内容:

我正在尝试通过一个按钮切换具有相同类的多个 div。目前,只有第一个 div 起作用,其余的被忽略了。我尝试将 .getElementById 更改为 .getElementsByClassName,但也没有起效。你能帮忙吗?这是我的代码。我已经尝试了两天了。 :/

按钮的代码:

<input onclick="change();myFunction()" type="button" value="Zeige Features" id="myButton1"></input>

用于在点击时更改按钮文本为“隐藏”/“显示”的代码(以德语为准):

<script>
function change() // 没有';' 在这里
{
    var elem = document.getElementById("myButton1");
    if (elem.value=="Zeige Features") elem.value = "Verstecke Features";
    else elem.value = "Zeige Features";
}
</script>

问题可能出在这里。以下是用于切换 div 的代码,但只有第一个 div 起作用:

<script>
function myFunction() {
  var x = document.getElementById("toggle-div");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
</script>

希望你能帮助我,谢谢!

英文:

I am trying to toggle multiple divs with same class via one button. At the moment, only the first div is doing the job and the rest gets ignored. I tried to change .getElementById to .getElementsByClassName but it also doesn´t do the trick. Can you please help? Here is my code. I´m trying since 2 days. :/

Code for Button:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;input onclick=&quot;change();myFunction()&quot; type=&quot;button&quot; value=&quot;Zeige Features&quot; id=&quot;myButton1&quot;&gt;&lt;/input&gt;

<!-- end snippet -->

Code for changing the text of button when clicked to "hide" / "show" (in German):

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;script&gt;function change() // no &#39;;&#39; here
{
    var elem = document.getElementById(&quot;myButton1&quot;);
    if (elem.value==&quot;Zeige Features&quot;) elem.value = &quot;Verstecke Features&quot;;
    else elem.value = &quot;Zeige Features&quot;;
}&lt;/script&gt;

<!-- end snippet -->

The problem should be perhaps here. That´s the code for toggling the divs but only the first div does it:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;script&gt;function myFunction() {
  var x = document.getElementById(&quot;toggle-div&quot;);
  if (x.style.display === &quot;block&quot;) {
    x.style.display = &quot;none&quot;;
  } else {
    x.style.display = &quot;block&quot;;
  }
} &lt;/script&gt;

<!-- end snippet -->

Hope u can help me, and thanks!

答案1

得分: 1

从您的onclick中移除分号并添加一个空格。

//新代码
<input onclick="change() myFunction()" type="button" value="Zeige Features" id="myButton1"></input>

按钮的文本将在点击时很容易改变。

<script>
function change() {
  var elem = document.getElementById("myButton1");

  if (elem.value === "Zeige Features") elem.value = "Verstecke Features";
  else elem.value = "Zeige Features";
} //函数闭合
</script>

使用getElementsByClass,它会返回一个数组,因此通过数组进行循环,逐个更改每个div的样式。

<script>
function myFunction() {
  var x = document.getElementsByClassName("toggle-div");

  for (var i = 0; i < x.length; i++) {
    if (x[i].style.display === "block") {
      x[i].style.display = "none";
    } else {
      x[i].style.display = "block";
    }
  }
}
</script>

您可以使用除了for之外的任何循环,或者您可以使用map()

英文:

Remove the semicolon from your onclick and add a space.

//New code
&lt;input onclick=&quot;change() myFunction()&quot; type=&quot;button&quot; value=&quot;Zeige Features&quot; id=&quot;myButton1&quot;&gt;&lt;/input&gt;

The text of Button will change pretty easily onclick.

&lt;script&gt;
function change()
{
var elem = document.getElementById(&quot;myButton1&quot;); 

    if (elem.value==&quot;Zeige Features&quot;) elem.value = &quot;Verstecke Features&quot;;
    else elem.value = &quot;Zeige Features&quot;;

}//function closed
&lt;/script&gt;

Use getElementsByClass, it will give an array, so loop through the array, and change the style of each div one by one.

&lt;script&gt;
function myFunction() 
{
  var x = document.getElementsByClass(&quot;toggle-div&quot;);

for( var i=0;i&lt;x.length;i++)
{
  if (x[i].style.display === &quot;block&quot;) {
    x[i].style.display = &quot;none&quot;;
  } else {
    x[i].style.display = &quot;block&quot;;
  }
}
} 
&lt;/script&gt;

You can use any loop other then for also, or you can use map()

答案2

得分: 0

这里有几个问题。
首先,您应该通过 class 来获取您的元素,如下所示:

     document.getElementsByClassName("name-of-toggle-divs-class");

这将返回一个 HTMLCollection,所以您想将它转换为数组,像这样:

    Array.from(document.getElementsByClassName("name-of-toggle-divs-class"));

然后对所有元素应用样式更改。继续:

    function myFunction(){
     const divArray = Array.from(document.getElementsByClassName("name-of-toggle-divs-class"));
     // 检测您将要使用的样式
     const displayStyle = divArray[0].style.display === 'block' ? 'none' : 'block';
     divArray.forEach(div => {
        div.style.display = displayStyle;
    });

您应该使用 class 标识,因为 id 会暗示您只有一个项目。如果有问题,请告诉我。

您还可以考虑将类别从项目中切换,将 class 定义为:

     .div-of-toggle-divs-class {
       //一些属性
       display: block;
       &.invisible {
           display: none;
       }
      }

只需按照上述相同的过程操作,并在 divArray 元素上使用 toggleClass 方法。尝试这个:

    <head>
         <style>
           .myClass {
                 border: 1px solid black;
                 margin-top: 2px;
                 width: 100%;
            }
          </style>
          <script>
                function myFunction(){
                const divArray = 
                Array.from(document.getElementsByClassName("myClass"));
               // 检测您将要使用的样式
               const displayStyle = divArray[0].style.display === 'block' ? 'none' : 'block';
              divArray.forEach(div => {
              div.style.display = displayStyle;
             }); 
          </script>
    </head>
    <body>
            <div class="myClass"></div>
            <div class="myClass"></div>
            <div class="myClass"></div>
            <button type="button" onclick="myFunction()">点击我</button>
    </body>
英文:

there are several problems here.
First of all you should get your element by class as it:

 document.getElementsByClassName(&quot;name-of-toggle-divs-class&quot;);

this will return an HTMLCollection, so you want to cast it to an array, like this:

Array.from(document.getElementsByClassName(&quot;name-of-toggle-divs-class&quot;));

And then apply the style change to ALL of the elements. Resuming:

function myFunction(){
 const divArray = Array.from(document.getElementsByClassName(&quot;name-of-toggle-divs-class&quot;));
 //Detecting the style you&#39;re going to use
 const displayStyle = divArray[0].display.style === &#39;block&#39; ? &#39;none&#39; : &#39;block&#39;;
 divArray.forEach(div =&gt; {
    div.style.display = displayStyle;
});

You should use class identifier because and id would suggest you have only one item. Let me know if you have problems.

You could also think of toggling class from your items defining class as:

 .div-of-toggle-divs-class{
   //some attributes
   display: block;
   &amp;.invisible{
       display: none;
   }
  }

To do this just follow the same process as above and use the toggleClass method on the divArray elements. Try this:

&lt;head&gt;
     &lt;style&gt;
       .myClass {
             border: 1px solid black;
             margin-top: 2px;
             width: 100%;
        }
      &lt;/style&gt;
      &lt;script&gt;
            function myFunction(){
            const divArray = 
            Array.from(document.getElementsByClassName(&quot;myClass&quot;));
           //Detecting the style you&#39;re going to use
           const displayStyle = divArray[0].display.style === &#39;block&#39; ? &#39;none&#39; : &#39;block&#39;;
          divArray.forEach(div =&gt; {
          div.style.display = displayStyle;
         }); 
      &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
        &lt;div class=&quot;myClass&quot;&gt;&lt;/div&gt;
        &lt;div class=&quot;myClass&quot;&gt;&lt;/div&gt;
        &lt;div class=&quot;myClass&quot;&gt;&lt;/div&gt;
        &lt;button type=&quot;button&quot; onclik=&quot;myFunction()&quot;&gt;CLICK ME&lt;/button&gt;
&lt;/body&gt;

答案3

得分: 0

好的,

这真是一个让人头疼的问题,但是我认为通过许多变通方法,我解决了它。以下是我想实现的内容:有三个按钮和三个 div。当我点击一个按钮时,所有三个 div 都会消失,而所有三个按钮的文本都会更改为“隐藏”。再次点击时,反之亦然。我希望这能帮助所有有类似需求的人。我认为在 CSS 中触发所有“类”要容易得多。这是我在 JavaScript 中迈出的第一步,对我来说就像是中文一样困难(我不会说它 :))。

<!-- 开始代码片段: js hide: false console: true babel: false -->

<!-- 语言: lang-js -->
// 切换所有按钮的文本

function change() {
  var x = document.querySelectorAll("#button");
  var i;
  for (i = 0; i < x.length; i++) {
    if (x[i].value == "Zeige Features") {
      x[i].value = "Verstecke Features";
    } else {
      x[i].value = "Zeige Features";
    }
  }
}

// 切换显示和隐藏的 div

function showhide() {
  var x = document.querySelectorAll("#toggle-div");
  var i;
  for (i = 0; i < x.length; i++) {
    if (x[i].style.display === "block") {
      x[i].style.display = "none";
    } else {
      x[i].style.display = "block";
    }
  }
}

<!-- 语言: lang-html -->
<!-- 插入 3 个按钮 -->

<input onclick="change();showhide()" type="button" value="Zeige Features" id="button"></input>
<input onclick="change();showhide()" type="button" value="Zeige Features" id="button"></input>
<input onclick="change();showhide()" type="button" value="Zeige Features" id="button"></input>

<!-- 插入 3 个 div -->

<div id="toggle-div"> div 1 </div>
<div id="toggle-div"> div 2 </div>
<div id="toggle-div"> div 3 </div>

<!-- 结束代码片段 -->

感谢 @pikachu_on_acid。你的方法是正确的,但是我仍然遇到了问题。如果你在开始时想要隐藏 div,可能会发现需要点击两次才能隐藏它们。在我的网站上,它们最初是隐藏的,因此它们首先会出现。如果你想反转这个效果,只需在 JavaScript 代码中将值从“block”、“none”、“block”更改为“none”、“block”、“none”。

谢谢你的帮助,致意!

英文:

Okay,

this was a pain in the ass but I think with a lot of workaround I solved it. Here is what I wanted to achive. Having three buttons and three divs. When I click one button alls three divs disappear and all three buttons change text to "hide". When click again, vice versa. I hope this helps everyone out there. I think to trigger all "classes" is in css much easier. These were my first steps in javascript and it was as difficult as chinese for me (don´t speak it :)).

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// Toggle all buttons texts
function change() {
var x = document.querySelectorAll(&quot;#button&quot;);
var i;
for (i = 0; i &lt; x.length; i++) {
if (x[i].value == &quot;Zeige Features&quot;) {
x[i].value = &quot;Verstecke Features&quot;;
} else {
x[i].value = &quot;Zeige Features&quot;;
}
}
}
// Toggle show and hide divs
function showhide() {
var x = document.querySelectorAll(&quot;#toggle-div&quot;);
var i;
for (i = 0; i &lt; x.length; i++) {
if (x[i].style.display === &quot;block&quot;) {
x[i].style.display = &quot;none&quot;;
} else {
x[i].style.display =
&quot;block&quot;;
}
}
}

<!-- language: lang-html -->

&lt;!--Inserting 3 buttons--&gt;
&lt;input onclick=&quot;change();showhide()&quot; type=&quot;button&quot; value=&quot;Zeige Features&quot; id=&quot;button&quot;&gt;&lt;/input&gt;
&lt;input onclick=&quot;change();showhide()&quot; type=&quot;button&quot; value=&quot;Zeige Features&quot; id=&quot;button&quot;&gt;&lt;/input&gt;
&lt;input onclick=&quot;change();showhide()&quot; type=&quot;button&quot; value=&quot;Zeige Features&quot; id=&quot;button&quot;&gt;&lt;/input&gt;
&lt;!--Inserting 3 divs--&gt;
&lt;div id=&quot;toggle-div&quot;&gt; div 1 &lt;/div&gt;
&lt;div id=&quot;toggle-div&quot;&gt; div 2 &lt;/div&gt;
&lt;div id=&quot;toggle-div&quot;&gt; div 3 &lt;/div&gt;

<!-- end snippet -->

Thanks @pikachu_on_acid. Youre approach was the right one but still I had issues with it. Don´t wonder if you have to click two times at the beginning when u want to hide the divs. In my site they are first hidden, so they appear fist. If you want to reverse that just change the values from "block" "none" "block" to "none" "block" "none" in the java code.

Thanks for your help and regards!

huangapple
  • 本文由 发表于 2020年10月26日 22:47:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64539427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定