2016-04-25 33 views
1

如何分別爲每個元素運行一個函數?爲每個元素分別運行函數?

所以,如果我點擊第一個open只有第一組應該打開。

$(document).on('click', "a.showdetails", function() { 
 
     $(".group").toggleClass("opened"); 
 
    });
.option{ 
 
    width: 200px; 
 
} 
 

 
.showdetails{ 
 
    display: block; 
 
} 
 

 
.group{ 
 
    display: none; 
 
    width: 200px; 
 
    height: 100px; 
 
    background: #f2f2f2; 
 
} 
 

 
.group.opened{ 
 
    display: block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<div class="option"> 
 
    <a href="#" class="showdetails">open</a> 
 
    <div class="group"></div> 
 
</div> 
 

 
<div class="option"> 
 
    <a href="#" class="showdetails">open</a> 
 
    <div class="group"></div> 
 
</div>

回答

4

您需要使用點擊的元素上下文來找到它的兄弟元素與類組:

var groupelements = $('.group'); 
$(document).on('click', "a.showdetails", function() { 
    var targetgroup = $(this).next('.group'); 
    groupelements.filter(targetgroup).removeClass("opened") 
    targetgroup.toggleClass("opened"); 
}); 

注意:您在這裏使用事件代表團。只有在動態加載元素a.showdetails時才應該使用它。否則使用.click來綁定靜態元素的點擊。

+0

你知道如何關閉活動組,如果其他組被打開? –

+0

@AlexanderHein:檢查更新的代碼。 –

+0

當您更改HTML元素佈局時,使用[JQuery method .next()](http://www.jqapi.com/#p=next)可能會成爲問題。但是通過父容器獲取元素是一種很好的做法。 – hmd

1

您需要先點擊Anchor獲取父級。當您更改HTML元素放置時,使用Jquery .next()可能會成爲問題。但是通過父容器獲取元素是一種很好的做法。

HTML:

<div class="option"> 
     <a href="#" class="showdetails">open</a> 
     <div class="group">hello 1</div> 
    </div> 

    <div class="option"> 
     <a href="#" class="showdetails">open</a> 
     <div class="group">hello 2</div> 
    </div> 

的JavaScript/JQuery的:

$(function() { 

     $(".showdetails").click(function() { 
     // Getting Parent of clicked Anchor 
     var parent_option = $(this).closest('.option'); 
     // Toggle class to the child .group class element. 
     $(".group", parent_option).toggleClass("opened");  
     }); 

    }); 

CSS:

.option{ 
     width: 200px; 
    } 

    .showdetails{ 
     display: block; 
    } 

    .group{ 
     display: none; 
     width: 200px; 
     height: 100px; 
     background: #f2f2f2; 
    } 

    .group.opened{ 
     display: block; 
    } 

工作演示:http://jsfiddle.net/ha97tmjf/

相關問題