[英]How to write accordion JavaScript in jQuery
I'm a beginner and I'm having a problem in writing my accordion JavaScript code to jQuery.我是初学者,在将手风琴 JavaScript 代码写入 jQuery 时遇到问题。
Here is my JavaScript code这是我的 JavaScript 代码
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
});
}
Here is the jQuery I tried这是我试过的 jQuery
$(".accordion").each(function(index) {
$(index).click(function() {
$(this).slideToggle("slow")
})
})
I tried it but it didn't work.我试过了,但没有用。 Does anyone know how to fix it?有谁知道如何修理它?
You can use this你可以用这个
$(".acc").on("click", function() { $('.acc>p').hide("slow"); // hide all $(this).find("p").show("slow"); /// show content })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="acc"> <p style="height: 60px; background: lime; display:none;">Hello World</p> <button>Change color</button> </div> <div class="acc"> <p style="height: 60px; background: lime; display:none;">Hello World</p> <button>Change color</button> </div>
There is no need to loop through elements using jQuery, it will do for you;)无需使用 jQuery 循环遍历元素,它会为你做的;)
$('.accordion').on('click',function(){
$(this).slideToggle("slow");
});
That's all!就这样!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.