Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

jquery - Best way to show and hide table when click a class with same class

How can i click any "a" element what has a class that matches a table and show and hide the corresponding table ? I'm capable of doing toggle and specifying each class , but i want something dynamic that will match up any "a" class to any table that has matching class.

Here is sample HTML

<a class="franchise_0001">CLICK AND SHOW table.franchise_0004</a>
<a class="franchise_0002">CLICK AND SHOW table.franchise_0003</a>
<a class="franchise_0003">CLICK AND SHOW table.franchise_0003</a>
<a class="franchise_0004">CLICK AND SHOW table.franchise_0003</a>

<table class="franchise_0001" style="display:none">SHOW WHEN a.franchise_0003 is clicked</table>
<table class="franchise_0002" style="display:none">SHOW WHEN a.franchise_0003 is clicked</table>
<table class="franchise_0004" style="display:none">SHOW WHEN a.franchise_0004 is clicked</table>
<table class="franchise_0003" style="display:none">SHOW WHEN a.franchise_0003 is clicked</table>

I dont want to declare each one like i have now because the classes can change and i need to have a way to match any up

 $("a.franchise_0004").click(function(){
    $("table.franchise_0004").toggle();
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get the class of any object using $.attr('class').

Get the class and pass it to the table.

$("a").click(function(){
    $("table."+$(this).attr('class')).toggle();
});

You can also use a class and toggle this, have a look:

$(document).on('click', 'a', function(e){
  e.preventDefault();
  $("table."+$(this).attr('class')).toggleClass('visible');
});
table {
  display: none;
}

table.visible {
  display: table;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="franchise_0001">CLICK AND SHOW table.franchise_0004</a><br />
<a class="franchise_0002">CLICK AND SHOW table.franchise_0003</a><br />
<a class="franchise_0003">CLICK AND SHOW table.franchise_0003</a><br />
<a class="franchise_0004">CLICK AND SHOW table.franchise_0003</a><br />
<br />
<table class="franchise_0001">
  <tr><td>SHOW WHEN a.franchise_0001 is clicked</td></tr>
</table>
<table class="franchise_0002">
  <tr><td>SHOW WHEN a.franchise_0002 is clicked</td></tr>
</table>
<table class="franchise_0003">
  <tr><td>SHOW WHEN a.franchise_0003 is clicked</td></tr>
</table>
<table class="franchise_0004">
  <tr><td>SHOW WHEN a.franchise_0004 is clicked</td></tr>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...