2016-09-18 118 views
1

這是針對用戶帳戶的。當用戶點擊編輯按鈕時,我想要一個編輯框顯示在按鈕所在的元素內部。jquery僅向此元素內的元素添加類

所以我有這個標記

<div class="col account"> 
    <strong>Account Settings</strong> 
     <div class="col"> 
      <span>Profile Status</span> 
       <p><?= $this->escape($this->status); ?></p> 
       <button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button> 
       <div class="edit-box"> 
        edit 1 
       </div> 
      </div> 
      <div class="col"> 
       <span>Name</span> 
       <p> <?= $this->escape($this->name); ?></p> 
       <button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button> 
       <div class="edit-box"> 
        edit 2 
       </div> 
      </div> 
      <div class="col"> 
       <span>Username</span> 
       <p><?= $this->escape($this->username); ?></p> 
       <button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button> 
       <div class="edit-box"> 
        edit 3 
       </div> 
      </div> 
      <div class="col"> 
       <span>Bio</span> 
       <p><?= $this->escape($this->bio); ?></p> 
       <button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button> 
       <div class="edit-box"> 
        edit 4 
       </div> 
      </div> 
      <div class="col"> 
       <span>Email</span> 
       <p><?= $this->escape($this->email); ?></p> 
       <button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button> 
       <div class="edit-box"> 
        edit 5 
       </div> 
      </div> 
      <div class="col"> 
       <span>Password</span> 
       <p>**********</p> 
       <button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button> 
       <div class="edit-box"> 
        edit 6 
       </div> 
      </div> 
     </div> 
    </div> 

然後,我有jQuery的

$(document).ready(function() 
{ 
    $('.edit-btn').click(function() 
    { 
     $('.edit-box').addClass('open'); 
    }); 
}); 

有沒有辦法一類僅添加到.edit箱,生活在同一個.COL爲.edit-btn?

這裏是一個js小提琴https://jsfiddle.net/y6ukq3th/

回答

2

是的,你可以使用.siblings('.edit-box')的類添加到誰擁有一個隨着點擊的按鈕的兄弟姐妹:

$(document).ready(function() { 
    $('.edit-btn').click(function() { 
     $(this).siblings('.edit-box').addClass('open'); 
    }); 
}); 

Demo

+0

啊謝謝我知道這是如此這種簡單的方法就是找不到選擇器。 – badsyntax

0
$(document).ready(function() { 

    $('.edit-btn').click(function() { 

     // clear all first (if you want to do) 
     // $('.edit-box').removeClass('open'); 

     // select in parent of target 
     $(this).parents('.col:first').find('.edit-box').addClass('open'); 

     // [or] select between siblings of target 
     // $(this).siblings('.edit-box').addClass('open'); 

     // [or] select next node of target 
     // $(this).next().addClass('open'); 
    }); 
}); 

https://jsfiddle.net/mvrv7065/