2016-11-11 79 views
0

正如您在HTML中看到的,該複選框被埋入我想要影響的類內的5個級別。當複選框被選中時,從複選框控制父級5個級別

$(".icheckbox").click(function() { 
 
    if ($(this).is(":checked")) { 
 
    $(this).closest(".gallery-item").addClass("active"); 
 
    } else { 
 

 
    } 
 
});
a.active { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a class="gallery-item" href="#"> 
 
    <div class="image"> 
 
    <ul class="gallery-item-controls"> 
 
     <li> 
 
     <label class="check"> 
 
      <input type="checkbox" class="icheckbox"> 
 
     </label> 
 
     </li> 
 
    </ul> 
 
    </div> 
 
</a>

我想是時候該複選框被選中上一個.active類添加到gallery-item類,並刪除它時是關閉(未選中)。但是我找不到跟Jquery遙遙無期的方式,並且讓事情變得更糟,根據檢查的attr我無法控制它,因爲檢查到的attr不會被添加。奇怪的。

這是CODEPEN。如果你這樣做是正確,灰色區域應該變成紅色並AFF與複選框

感謝小夥子們

+0

'$(本).closest(」 gallery-。項目「)會找到包含的項目。 – Barmar

+0

沒有理由爲你的例子使用codepen。在這裏發佈代碼作爲[Stack Snippet](http://meta.stackoverflow.com/questions/270944/feedback-requested-stack-snippets-2-0) – Barmar

+0

@Barmar所以沒有檢查attr,我怎樣纔能有條件地做這個?哦,我喜歡CODEPEN,因爲我一直回到舊的代碼修復和類似的東西。我付錢,不妨使用它。 – LOTUSMS

回答

0

您需要刪除其他

$(document).ready(function(){ 
    $(".icheckbox").click(function() { 
    if ($(this).is(":checked")) { 
     $(this).closest(".gallery-item").addClass("active"); 
    } else { 
     $(this).closest(".gallery-item").removeClass("active"); 
    } 
    }); 
}); 

http://jsbin.com/zikomagike/edit?html,css,js,console,output

類,如果你想要觀察更改,請使用.change()。即使其他某個函數改變了這個類而不是輸入,它也會被觸發。

最好添加一個name屬性,並在代碼中使用它:$("input[name='chkbox']")

HTML

<a class="gallery-item" href="#"> 
    <div class="image"> 
    <ul class="gallery-item-controls"> 
     <li> 
     <label class="check"> 
      <input name="chkbox" type="checkbox" class="icheckbox"> 
     </label> 
     </li> 
    </ul> 
    </div> 
</a> 

JS:

$(document).ready(function(){ 
     $("input[name='chkbox']").change(function() { 
     if ($(this).is(":checked")) { 
      $(this).closest(".gallery-item").addClass("active"); 
     } else { 
      $(this).closest(".gallery-item").removeClass("active"); 
     } 
     }); 
    }); 
相關問題