如何检查jQuery中是否已选中复选框?

2021年3月18日14:31:09 发表评论 677 次浏览

prop()和is()方法是我们可以通过两种方式检查是否在jQuery中选中了一个复选框.

prop():此方法提供了一种简单的方法来跟踪复选框的状态。它在每种情况下都可以正常工作, 因为每个复选框都有选中的属性, 用于指定其选中或未选中状态。

is():这种方法也非常简单易用。通过使用此功能, 我们可以轻松找到是否选中了复选框。

使用jQuery prop()方法:

语法如下:

$(selector).prop(parameter)

参数:这里的参数是复选框的当前状态。

示例1:

<!DOCTYPE html>
< html >
  
< head >
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
   </ script >
</ head >
  
< body >
     < div style="width: 80px;
             height: 80px;
             padding: 10px;
             border: 2px solid green;">
        
         < input type = "checkbox" 
                name = "radio1"
                checked />
         < script >
             $(document).ready(function() {
                 $("#but").click(function() {
                     if ($("input[type=checkbox]").prop(
                       ":checked")) {
                         alert("Check box in Checked");
                     } else {
                         alert("Check box is Unchecked");
                     }
                 });
             });
         </ script >
  
         < br >
  
         < button style = "margin-top:10px"
                 id = "but" 
                 type = "submit" >
           Submit
       </ button >
     </ div >
</ body >
  
</ html >

输出如下:

在单击按钮之前, 未选中复选框:

如何检查jQuery中是否已选中复选框?1

单击按钮后:

如何检查jQuery中是否已选中复选框?2

使用jQuery is()方法:

句法 :

$(selector).is(parameter)

参数:这里的参数是复选框的当前状态。

示例2:

<!DOCTYPE html>
< html >
  
< head >
     < style >
         div {
             width: 80px;
             height: 80px;
             padding: 10px;
             border: 2px solid green;
         }
          
         button {
             margin-top: 10px;
         }
     </ style >
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
   </ script >
  
</ head >
  
< body >
     < div >
         < input type = "checkbox"
                name = "radio1" 
                checked />
         < script >
             $(document).ready(function() {
                 $("#but").click(function() {
                     if ($("input[type=checkbox]").is(
                       ":checked")) {
                         alert("Check box in Checked");
                     } else {
                         alert("Check box is Unchecked");
                     }
                 });
             });
         </ script >
  
         < br >
  
         < button id = "but" 
                 type = "submit" >
           Submit 
       </ button >
     </ div >
</ body >
  
</ html >

输出如下:

单击"单击按钮之前"复选框:

如何检查jQuery中是否已选中复选框?3

单击按钮后:

如何检查jQuery中是否已选中复选框?4

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: