2012-11-13 2 views
0

페이지가로드 된 후이 기능이 필요합니다. 오류가 누락되었습니다. before 문 오류. 또한 체크 박스 toggle-all을 "checked"로 클릭했을 때 테이블 체크 박스의 클래스를 true로 체크하고 모든 체크 박스를 다시 클릭하면 체크 된 모든 체크 박스를 false로 표시합니다. 대괄호로 잘못 입력 한 것 같습니다.클릭 후 테이블에서 체크 박스를 토글합니다.

$(document).ready(function() { 
    $('#toggle-all, input:checkbox').click(
    function() { 
     $('#table, :checkbox').attr(':checked','checked').true); 
    },function(){ 
     $('#table :checkbox').attr(':checked').false); 
    } 
); 
}); 



<section id="main"> 
    <form id="task-list"> <input id="toggle-all" name="toggle-all" type="checkbox" /> 
     </form> 
</section> 

<table class="table" > 
    <tr> 
     <td><input type="checkbox" class="checkall" />item.todo </td> 
     <td> item.name</td><td> 
    </tr> 
...... more rows 
</table> 
+0

jsfiddle.net에 코드를 입력하면 쉽게 도움이됩니다. –

+0

참고 : 두 가지 기능을 클릭 할 수는 없습니다. 첫 번째는 #table 및 체크 박스를 참조하고, 두 번째는 #table (# 테이블이 존재하지 않음)의 체크 박스입니다. 테이블 않습니다). attr 대신 prop를 사용해야하고 ".false"또는 ".true"를 사용하여 propr을 사용하지 마십시오. 어쨌든 아래 작업 해결책. –

답변

1

간단한 해결책 :

$(document).ready(function() { 

    $("#toggle-all").click(function() { 
     $(".table input:checkbox").each(function() { 
      $(this).prop("checked", !$(this).prop("checked")); 
     }); 
    }); 

}); 

좀 더 방탄 (항상 함께 모든 체크 박스를 토글) :

$(document).ready(function() { 

    $("#toggle-all").click(function() { 
     $(".table input:checkbox").prop("checked", $(this).prop("checked")); 
    }); 

});​ 

데모 : 당신이 http://jsfiddle.net/Ck43Z/1/

1

를 사용하는 attr() 및 prop()는 입력의 상태를 가져오고 attr()은 기본 상태를 나타냅니다 (th e HTML) 반면 prop()는 현재 상태를 나타냅니다 (클릭하면 변경됩니다).

새 상태를 설정하는 데 사용하는 경우 동일한 작업을 수행합니다. 그러나 'checked'값을 설정하기 위해 prop()를 사용하는 습관을 갖는 것이 좋습니다.

$('#toggle-all').click(function() { 
    $('table input:checkbox').prop('checked', $(this).is(':checked')); 
}); 

이 경우 명령문, 우리는 첫번째 지점에 있다면, 식 $ (이)의 성격을 통해 "(.is는, 때문에

$('#toggle-all').click(function() { 
    if ($(this).is(':checked')) { 
     $('table input:checkbox').prop('checked', true); 
    } else { 
     $('table input:checkbox').prop('checked', false); 
    } 
}); 

을 작성하기위한 단지 속기 : 체크 ") 어쨌든 사실이며, 우리가 두 번째 지점에 있다면 그것은 틀렸을 것입니다. 그래서, 우리가 'true'와 'false'라고 썼을 때, 두 경우 모두 $ (this) .is ("checked :")를 쓸 수있었습니다. 이렇게 한 후에 두 브랜치는 똑같은 것을 말하기 때문에 더 이상 if 문에 쓰지 않아도됩니다.

$ (this)는 클릭 한 요소 (즉, 확인란)를 나타냅니다. jQuery에서 이벤트를 참조하려면 다음을 수행하십시오.

$('.element').click(function(e) { 
    // the variable e now refers to the event 
}); 
관련 문제