簡體   English   中英

jQuery幫助,以檢查選中的孩子的父母

[英]jQuery help with checking parent of checked child checkbox

我在其中有一個主行和其他一些行,如下所示:

[checkbox]  Main heading row  
            [checkbox] first child row  
            [checkbox] second  child row  

當我單擊子行時,它應自動檢查父(主)行。 問題是,我第一次單擊它時不會對其進行檢查。 我必須先檢查第一個子行,然后取消選中第一個子行,然后再次檢查第一個子行以獲取父(主)行。 我希望所有子行都被檢查后立即檢查父行。

我正在使用以下代碼

function checkbox_click(){

  var n = event.srcElement;
  if(n.parentElement.id == "row"){
   n = n.parentElement;
  }
  if(n.id == "row"){
   alert("ID: 1");
   n.rs = n.parentElement;
   if(this.multiSelect == 0){ // single select
    alert("ID: 2");
    n.all[0].checked = 1;
    this.selectedRows = [ n ];
    if(this.lastClicked && this.lastClicked != n){
     this.lastClicked.all[0].checked = 0;
     this.lastClicked.style.color = "000099";
     this.lastClicked.style.backgroundColor = "";
    }
   } else {
    alert("ID: 3");
    n.all[0].click();


   }
   if(this.parentElement == pg.procs) {
    alert("ID: 4");
    var terminate = false;
    var counter = 0;
   if(n.className == "proc") {
    alert("ID: 5");
     z = n.nextSibling;


     while(z.id == "row" && z.className != "proc" && !terminate) {
      alert("ID: 6");
      z.all[0].checked = 0;
      z.style.backgroundColor = z.className == "w" ? "ffffff" : "ffffcc";
      counter++;
      if(counter > 1000) terminate = true;
      z = z.nextSibling;
     }
    } else {


     $(".row input").change(function() {
      alert("ID: 7");
         var $row= $(this).closest(".row");
         var $main_row = $row.prev('.proc').length ? $row.prev('.proc') : $row.prevUntil(".proc").prev();
         $main_row.find(":checkbox").attr("checked", function(i,attr) {
             return $main_row.nextUntil('.proc').filter(':has(input:checked)').length ? "checked" : false;
         });
     });

     $(".proc input").change(function() {
      alert("ID: 8");

         $(this).closest(".proc").nextUntil('.proc').children(':checkbox').attr('checked', this.checked);
     });

    }

如果要在選中一個子復選框時選中父復選框,我建議為子復選框使用一個通用類,為父復選框使用一個唯一的id屬性(或將其存儲為變量)。

假設您有一個結構化的HTML文檔,其中包含以下內容:

<div>
    <input type="checkbox" name="ckparent" id="ckparent" />
    <label for="ckparent">Parent</label>

    <div>
        <input type="checkbox" name="ckchild1" id="ckchild1" class="ckchild" />
        <label for="ckchild1">Child 1</label>
    </div>

    <div>
        <input type="checkbox" name="ckchild2" id="ckchild2" class="ckchild" />
        <label for="ckchild2">Child 2</label>
    </div>
</div>

然后,您可以編寫以下jQuery代碼,以在選中任何一個子級時選中父級復選框:

$('input:checkbox.ckchild').click(function(event) {
    var checked = $(this).is(':checked');

    if (checked) {
        $('#ckparent').attr('checked', true);
    }
});

編輯:更改和單擊事件的觸發順序與實際何時更改選中屬性有關,取決於您使用的瀏覽器-您定位的瀏覽器是什么?

暫無
暫無

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

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