Toggle multiple Div names/content by one button click

社会主义新天地 提交于 2019-12-25 03:42:04

问题


i have 4 different divs in german. By clicking a button, i want to hide the german divs and instead show the english divs, which are hidden before.

There are ways to change between 2 divs, but how can i change mulitple divs at the same time by clicking one time on one button?


回答1:


You'll need JavaScript
or for an easier approach a JavaScript library like jQuery.

The basic approach is to add data-* attributes and classes to your elements:

<button class="langButton" data-language="en">EN ARTICLES</button>
<button class="langButton" data-language="de">DE ARTICLES</button>
<button class="langButton" data-language="it">IT ARTICLES</button>

<div class="article en">En 1...</div>
<div class="article en">En 2...</div>
<div class="article de">De 1...</div>
<div class="article de">De 2...</div>
<div class="article it">It 1...</div>
<div class="article it">It 2...</div>

than your jQuery might look like:

$(function() {   // Document is now ready to be manipulated

   // Cache all .article elements
   var $articles = $('.article');

   $(".langButton").click(function(){
       // Get the "en", "de" or "it" value
       var language = $(this).attr("data-language");
       // Hide all articles
       $articles.hide();
       // Show only the ones that have the ."language" related class
       $("."+ language ).show();
   });

});

Here's a live jsBin example you can play with or even download




回答2:


Are you restricted to not use a framework like jQuery? jQuery offers multiple methods to run your code on more than one selected elements.

Here is a basic working solution in pure javascript for you:

var shown = 'english';

function swap() {
    if (shown === 'english') {
       document.getElementById('german-1').style.display = "inline-block";
       document.getElementById('german-2').style.display = "inline-block";
       document.getElementById('german-3').style.display = "inline-block";
       document.getElementById('english-1').style.display = "none";
       document.getElementById('english-2').style.display = "none";
       document.getElementById('english-3').style.display = "none";
       shown = 'german';
   } else {
       document.getElementById('english-1').style.display = "inline-block";
       document.getElementById('english-2').style.display = "inline-block";
       document.getElementById('english-3').style.display = "inline-block";
       document.getElementById('german-1').style.display = "none";
       document.getElementById('german-2').style.display = "none";
       document.getElementById('german-3').style.display = "none";
       shown = 'english';
   }
};

Link to jsfiddle: https://jsfiddle.net/v2k3rzge/

Hope it helps



来源:https://stackoverflow.com/questions/28946756/toggle-multiple-div-names-content-by-one-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!