[英]Is there a better way to traverse the dom than call parent().parent()?
我將此作為我較大代碼的一部分,這看起來很丑陋且不切實際
if (!$(this).closest( "li" ).parent().parent().hasClass('mod-left') ) {
$(this).closest( "li" ).parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true);
$(this).closest( "li" ).parent().parent().parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true);
$(this).closest( "li" ).parent().parent().parent().parent().parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true);
$(this).closest( "li" ).parent().parent().parent().parent().parent().parent().parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true);
}
有一個更好的方法嗎?
您可以使用
$(this).parents('selector')
如果您在dom樹中有一個以上的類或ID,則可以參考。
希望這個能對您有所幫助
$(this).parents('.class-of-any-parent').append('this is working');
有關更多詳細信息,請在此處訪問jquery parent()的文檔
$(this).parents('.class-of-any-parent').find('#checkbox-id').prop('checked',true);
//這將在選定的父級中搜索checkbox-id並將其選中
操作DOM時,永遠不要依賴HTML的結構和層次結構。 在前端工作中,您可以認為HTML是您的結構/布局層,CSS是您的表示/樣式層,而JS是您的邏輯。 每個都應該分開。
當您使用$(this).parent().parent();
移動元素會破壞您的代碼。
我想您要在此處執行的操作是在每個父級中的第一個容器中使用.checkbox
類.wf-check
帶有.checkbox
類的復選框。
如果是這樣,您可以考慮這樣做:
$('.checkbox:first-child .wf-check', '.container').prop('checked', true);
您需要做的就是將上面的.container
替換為包含所有復選框的最高父類。
這是一個工作演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.