0

我是编程新手,并试图简化一些 jquery/javascript 代码,但我没有取得太大的成功。我尝试调整此处找到的解决方案:jQuery Simplify

...但同样,没有成功。

这是我的jQuery代码:

<script>
$(document).ready(function(){

$("#hide01").click(function(){
$(".content01").hide();
});

$("#show01").click(function(){
$("p").hide();
$(".content01").show();
});

$("#hide02").click(function(){
$(".content02").hide();
});

$("#show02").click(function(){
$("p").hide();
$(".content02").show();
});

});
</script>

和 HTML:

<button id="hide01">Hide</button>
<button id="show01">Show</button>

<button id="hide02">Hide</button>
<button id="show02">Show</button>

<p class="content01">Content 01</p>

<p class="content02">Content 02</p>

该解决方案有效,但我需要 40 个按钮/内容块...

任何人都可以帮忙吗?谢谢!

4

2 回答 2

7

我会将 HTML 更改为:

<button class="btn_hide" data-id="01">Hide</button>
<button class="btn_show" data-id="01">Show</button>

<button class="btn_hide" data-id="02">Hide</button>
<button class="btn_show" data-id="02">Show</button>

<p id="content01">Content 01</p>
<p id="content02">Content 02</p>

那么你的 jQuery 可以是:

$(".btn_hide").click(function() {
    $("#content"+this.getAttribute("data-id")).hide();
});
$(".btn_show").click(function() {
    $("p").hide();
    $("#content"+this.getAttribute("data-id")).show();
});
于 2013-03-20T16:11:54.747 回答
2

使用 jQuery,您可以堆叠选择器 IE:

 $("#hide01, #show01").click(function(){
    $(".content01").hide();
 });

但就个人而言,我不会使用 ID,而是为此使用一个类:

  <button id="hide01" class="hide">Hide</button>
  <button id="show01" class="show">Show</button>
  <button id="hide02" class="hide">Hide</button>
  <button id="show02" class="show">Show</button>
  <button id="hide03" class="hide">Hide</button>
  <button id="show04" class="show">Show</button>

JS

 $(".hide").click(function(){
    $(".content01").hide();
 });
 //Etc Etc..
于 2013-03-20T16:11:37.657 回答