2013-05-08 30 views
-1

我有一個問題,試圖訪問我的跨度上幾個級別的複選框。jquery目標父級上兩級複選框

<div class="control-group"> 
<input type="checkbox" name="employed_now" id="employed_now" class="checkbox-msg"/> 
<label><span class="label label-success checkbox-msg">Yes</span>employed_now</label> 

當點擊span.checkbox-msg,我想對DOM遍歷高達和檢查/取消選中該複選框。

下面的代碼無法正常工作:

$(document).on('click', 'span.checkbox-msg', function (e) { 
     e.preventDefault(); 
     $(this).parent().find('input:checkbox').attr('checked','checked'); 
    }); 

我無法使用/目標只是「複選框,味精」,因爲在頁面上的其他類的類名。

我該如何將父母>父母作爲複選框?

+0

這個複選框在哪裏改變,你只在html中顯示。 – 2013-05-08 05:33:41

+0

@DavidThomas - 有一個複選框。 span標籤將檢查/取消選中該項目。複選框是id = employed_now。 – 2013-05-08 15:49:19

回答

2

您可以使用.siblings().closest()哪個適合你,你可以使用.prop()檢查,並取消:

$(this).parent().siblings('input:checkbox').prop('checked', true); 

$(this).closest('.control-group').find('input:checkbox').prop('checked', true); 

Findout both here

0

試試這個:

$(document).on('click', 'span.checkbox-msg', function (e) { 
    e.preventDefault(); 
    $(this).before('input:checkbox').prop('checked',true); 
}); 
2

你可以這樣來做:

$(document).on('click', 'span.checkbox-msg', function (e) { 
     e.preventDefault(); 
     $('input:checkbox', $(this).closest('div')).attr('checked','checked'); 
    }); 

但是你可能只需要添加for='employed_now'屬性您<label>,並具有相同的功能,無需jQuery的。