我尝试添加多个按钮,当我单击一个按钮时,其余的按钮也会被单击。
如何让每个按钮单独切换?
另外,如何在页面加载时默认将它们全部隐藏?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideToggle demo</title>
<style>
p {
width: 400px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button>Toggle 1</button>
<p>
Text 1
</p>
<button>Toggle 2</button>
<p>
Text 2
</p>
<script>
$( "button" ).click(function() {
$( "p" ).slideToggle( "slow" );
});
</script>
</body>
</html>
编辑:
谢谢大家,每个代码都有效!
只有最后一件事,如何在主按钮中有多个按钮及其唯一段落?
例:
[MainButton.A] <--(Shows additional buttons when clicked)
[ButtonA.1] <--(Shows it's own paragraph when clicked, same as the rest)
[ButtonA.2]
[MainButton.B]
[ButtonB.1]
[ButtonB.2]
试试这样...
<script>
$(document).ready(function(){
$("p").hide();//hides all <p> initially shows only button clicked..
$( "button" ).click(function() {
$(this).next( "p" ).slideToggle( "slow" );
});
});
</script>
小提琴 https://jsfiddle.net/ohes689y/
问题不在于所有按钮都被点击;而是每次单击按钮时,所有段落元素都会作。
@ArunPJohny的评论有解决方案:
$("button").click(function() {
$(this).next("p").slideToggle( "slow" );
});
这样做是选择下一个<p>
元素,而不是所有元素。请注意此处的.next()
选择器。
这是你的答案
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideToggle demo</title>
<style>
p {
width: 400px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button class="btncls">Toggle 1</button>
<p>
Text 1
</p>
<button class="btncls">Toggle 2</button>
<p>
Text 2
</p>
<script>
$(".btncls").click(function() {
$(this).next().slideToggle( "slow" );
});
</script>
</body>
</html>