[英]Toggling an element that appears twice on a page
I am working with an html component that appears twice on a page. 我正在使用在页面上出现两次的html组件。
The issue I am having is that when I click one component to toggle it's content (like an accordion) both components toggle simultaneously. 我遇到的问题是,当我单击一个组件以切换其内容时(例如手风琴),两个组件同时切换。
How can I rewrite the JS to toggle each component when I click them separately, without giving the components different classes and rewriting the js twice? 当我分别单击它们时,如何给JS重写以切换每个组件,而又不给组件提供不同的类并重写JS两次呢?
This is what I have so far; 这是我到目前为止所拥有的;
var bindEventsToUI = function () {
$(".details").click(function(e){
$(".content").slideToggle("slow", function() {
$(e.target).hide().siblings().show();
});
});
};
Try this: 尝试这个:
$(".details").click(function(e) { $(this).children(".content").slideToggle("slow"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='details'>Testing 123 <div class='content'>> Content 123</div> </div> <div class='details'>Testing 456 <div class='content'>> Content 456</div> </div>
You will need to have a different identifier for each element. 您将需要为每个元素使用不同的标识符。 I would recommend an
id
: 我会推荐一个
id
:
var bindEventsToUI = function () {//element) {
$("#id1 .details").click(function(e){
$("#id1 .content").slideToggle("slow", function() {
$(e.target).hide().siblings().show();
});
});
$("#id2 .details").click(function(e){
$("#id2 .content").slideToggle("slow", function() {
$(e.target).hide().siblings().show();
});
});
//..and so on
};
Or, you could use the closest
function: 或者,您可以使用
closest
函数:
var bindEventsToUI = function () {//element) {
$(".details").click(function(e){
$(this).closest(".content").slideToggle("slow", function() {
$(e.target).hide().siblings().show();
});
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.