Toggle div with same id as click

I am trying to switch multiple divs myself.

Currently, it works as it should, but not completely. What I'm trying to do is toggle the div that matches the element with a click - but I also want to be able to click the element again and hide the corresponding div.

How can i achieve this? Feel free to use jsFiddle http://jsfiddle.net/oczfefaa/9/

$(document).ready(function() { 
  $("ul.menu li a").on("click", function(e) {
    $("div").addClass("hide");
    e.PreventDefault;
    var grabID = $(this).attr( "href" );
    $('div' + grabID).toggleClass("hide");
  });
});
+4
source share
3 answers

: hide div, ( div), , , toggleClass div, . hide div, .

$(document).ready(function() {   
    $("ul.menu li a").on("click", function(e) { 
        e.PreventDefault; 
        var grabID = $(this).attr( "href" );                                
        $('div' + grabID).toggleClass("hide");
        $("div").not('div' + grabID).addClass("hide");//hide all div except clicked one.
    });

});

JSFiddle

+2

og togleClass

$(document).ready(function() {   
    $("ul.menu li a").on("click", function(e) { 
        $("div").addClass("hide");
        e.PreventDefault; 
        var grabID = $(this).attr( "href" );                                
        $('div' + grabID).toggle("hide");

    });

});

0

on every click u add class and toggle can only delete the class ...

$(document).ready(function() {   
$("ul.menu li a").on("click", function(e) { 
    e.PreventDefault; 
    var grabID = $(this).attr( "href" );                                
    $('div' + grabID).toggle("hide");
});});
0
source

Source: https://habr.com/ru/post/1612583/


All Articles