我从 w3school 找到了一个示例程序,并设法对其进行了编辑。但问题是,它太耗费代码了,我想要的是这段代码的简短版本。是否可以? (我试图将 div 放入 php include 中,我使用了一个切换功能和多个按钮,但是一旦我点击一个按钮,所有的 div 都会显示)。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#p1").hide();
$("#p2").hide();
$("#p3").hide();
$("#p4").hide();
$("#button1").click(function(){
$("#p1").toggle();
});
$("#button2").click(function(){
$("#p2").toggle();
});
$("#button3").click(function(){
$("#p3").toggle();
});
$("#button4").click(function(){
$("#p4").toggle();
});
});
</script>
</head>
<body>
<div id="p1">
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</div>
<button id="button1">Toggle</button>
<br>
<br>
<br>
<div id="p2">
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</div>
<button id="button2">Toggle</button>
<br>
<br>
<br>
<div id="p3">
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</div>
<button id="button3">Toggle</button>
<br>
<br>
<br>
<div id="p4">
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</div>
<button id="button4">Toggle</button>
<br>
<br>
<br>
</body>
</html>
最佳答案
您可以先重新组织 HTML,并使用更短的脚本。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".msg").hide();
$(".toggle").click(function(){
$(this).parent( "div" ).find(".msg").toggle();
});
});
</script>
</head>
<body>
<div>
<div class="msg">
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</div>
<button class="toggle">Toggle</button>
</div>
<br><br><br>
<div>
<div class="msg">
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</div>
<button class="toggle">Toggle</button>
</div>
<br><br><br>
<div>
<div class="msg">
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</div>
<button class="toggle">Toggle</button>
</div>
<br><br><br>
<div>
<div class="msg">
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</div>
<button class="toggle">Toggle</button>
</div>
<br><br><br>
</body>
</html>
关于javascript - jquery 切换多个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35075642/