有人可以让这个脚本更简单吗?

时间:2015-12-03 10:27:22

标签: javascript css hide show

我目前正在使用2个javascript函数,只需要一个。

<!DOCTYPE html>
<html>
<head>

<style type="text/css">

div.menubox1 {
background-color: #323232;
height: 50px;

}

div.menubox2 {
background-color: #323232;
height: 50px;

}

div.relative {
position: relative;
top: 26%;
left: 7.6%;
border: 0px;
width: 200px;
}

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div.menubox1").click(function(){
        $("p1").toggle();
    });
});
</script>

<script>
$(document).ready(function(){
    $("div.menubox2").click(function(){
        $("p2").toggle();
    });
});
</script>

</head>
<body>

<div class="menubox1"><div class="relative"> » test 1</div></div>
<p1>This is a paragraph with little content.</p1>

<div class="menubox2"><div class="relative"> » test 2</div></div>
<p2>This is another small paragraph.</p2>

</body>
</html>

这确实有效,例如每个DIV都会显示/隐藏段落,但我可以调整脚本以直接从受影响的DIV中获取信息并进行显示/隐藏操作。

修改

我想我已经解释了这个错误。我指的是这部分:

   <script>
    $(document).ready(function(){
        $("div.menubox1").click(function(){
            $("p1").toggle();
        });
    });
    </script>

    <script>
    $(document).ready(function(){
        $("div.menubox2").click(function(){
            $("p2").toggle();
        });
    });
    </script>

当然需要更改为1个功能而不是2个或者需要显示/隐藏的DIV。

3 个答案:

答案 0 :(得分:1)

使用ONE类并将事件处理程序添加到类中 - 要区分div,请使用ID。同时将<p1 / <p2更改为<p id="p1"<p id="p2"

&#13;
&#13;
$(function() {
  $("div.menubox").on("click",function() {
    var idx = this.id.replace(/menubox/, ""); // or use data-idx attribute
    $("#p" + idx).toggle(); // or $(this).next().toggle(); if p is always after the div
  });
});
&#13;
div.menubox {
  background-color: #323232;
  height: 50px;
}
div.relative {
  position: relative;
  top: 26%;
  left: 7.6%;
  border: 0px;
  width: 200px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div class="menubox" id="menubox1">
  <div class="relative">» test 1</div>
</div>
<p id="p1">This is a paragraph with little content.</p1>

<div class="menubox" id="menubox2">
  <div class="relative">» test 2</div>
</div>
<p id="p2">This is another small paragraph.</p2>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

I think you are looking for the following:

https://jsfiddle.net/sq6znmm0/

$(document).ready(function(){
    $("div.menubox").click(function(){
        $(this).next('p').toggle();
    });
});

Be aware that p1 and p2 are not valid HTML tags. I also removed the numbers from your menubox, so the jQuery matches both.

答案 2 :(得分:0)

$(document).ready(function(){
    function attachClickHandlers(clickElement, toggleElement) {

            $(clickElement).click(function(){
                $(toggleElement).toggle();
            });

    }

    attachClickHandlers("div.menubox1", "p1");
    attachClickHandlers("div.menubox2", "p1");
});

虽然一个好的做法也是使用类似mplungjan建议的特定css类