如何多次使用我的jQuery slidetoggle?

时间:2016-04-04 13:02:47

标签: javascript jquery html

我有我的jQuery slidetoggle,它适用于第一个<div>但是当添加更多翻转和面板时,它不会起作用。它必须像this。 我点击上面的一个就可以了。第二个甚至没有反应。我该如何解决这个问题?

完整代码:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js
</script>
<script> 
$(document).ready(function(){
$("#flip").click(function(){
    $("#panel").slideToggle("slow");
});
});
$(document).ready(function(){
$("#flip1").click(function(){
    $("#panel1").slideToggle("slow");
});
});
</script>

<style> 
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
display: none;
}

#panel1, #flip1 {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel1 {
padding: 50px;
display: none;
}
</style>
</head>
<body>

<div id="flip">Click to slide the panel down or up</div>
<div id="panel">Hello world!</div>

<br><br>

<h1 style="text-align: center;">This example below won't work. Why not?</h1><br>    <br>
<div id="flip">Click to slide the seconds panel down or up</div>
<div id="panel">Hello world!</div>

<br><br>

<h1 style="text-align: center;">To fix this I could try using different names for the flip and panel such as flip1 and panel1</h1><br><br>


<div id="flip1">Click to slide the panel down or up</div>
<div id="panel1">Hello world!</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

ID必须是唯一的demo

$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideToggle("slow");
    });
    $("#flip1").click(function(){
        $("#panel1").slideToggle("slow");
    });
});

请使用jsfiddle,如下better version :)