簡體   English   中英

遍歷父節點中輸入的子級

[英]Iterate over children of inputs in parent node

<div class="parent">
    <div class="click"></div>
    <div class="subdiv">
        <input value="1">
        <input value="2">
    </div>
</div>

我有以下代碼,並且在click div上有onclick事件。 現在,我要遍歷此特定父div所有input s(有很多)。

所以我寫了這樣的東西:

$(this).parent().children('.subdiv input').not(':checked').length

根據未選中的input s,它應該輸出類似於1或2的值。 但它始終顯示為0。

為什么會這樣?

另外,如何檢查/取消所有檢查?

$(this).parent().find('.subdiv input').not(':checked').each(function() {
    // $(this) is undefined, or shows 0
});

首先,您應該將這些輸入聲明為復選框:

<input type="checkbox" value="1" />

然后,單擊.parent元素:

$('.parent').on('click', function() {
    // alert the number of checked checkboxes
    alert($(this).find('input[type="checkbox"]:checked').length);
});

為了檢查復選框,請使用prop()函數:

$('input[type="checkbox"]').prop('checked', true); // sets input to checked state

為了獲得復選框的值:

var value = $('input[type="checkbox"]').val();

DEMO

 $('.parent').on('click', function() { var n = $(this).find('input[type=checkbox]:checked').length; alert('There are ' + n + ' checked checkboxes'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="parent"> <div class="click"></div> <div class="subdiv"> <input type="checkbox" value="1"> <input type="checkbox" value="2" checked> </div> </div> 

假設所有輸入均為復選框或可檢查的任何內容,請使用以下1>未選中輸入的數量

$(this).parent().find('input:checked').length

1>未選中任何輸入

$(this).parent().find('input').not(':checked').length

默認情況下, input s為text 並且checked屬性不適用於文本字段。 它應該是復選框或單選。 嘗試-

<div class="subdiv">
  <input type="checkbox" value="1">
  <input type="checkbox" value="2">
</div>

輸入文本沒有選中/未選中屬性。 您需要將類型定義為輸入元素的復選框:

<input type="checkbox" value="1">
<input type="checkbox" value="2">

您也可以縮小選擇器的范圍,以取消選中以下復選框:

$(this).parent().find('input:not(:checked)').each(function() {
 // $(this) is undefined, or shows 0
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM