gpt4 book ai didi

javascript - 有人可以使这个脚本更简单吗?

转载 作者:行者123 更新时间:2023-11-28 16:32:33 25 4
gpt4 key购买 nike

我目前正在使用 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。

最佳答案

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

$(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
});
});
div.menubox {
background-color: #323232;
height: 50px;
}
div.relative {
position: relative;
top: 26%;
left: 7.6%;
border: 0px;
width: 200px;
}
<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>

关于javascript - 有人可以使这个脚本更简单吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34063466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com