jQuery:测试是否未选中复选框 [英] jQuery: Test if checkbox is NOT checked

查看:83
本文介绍了jQuery:测试是否未选中复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚这一点.我有两个复选框(将来会有更多复选框):

I'm having trouble figuring this out. I have two checkboxes (in the future will have more):

  • checkSurfaceEnvironment-1
  • checkSurfaceEnvironment-2
  • checkSurfaceEnvironment-1
  • checkSurfaceEnvironment-2

基本上,我想编写一条if语句并测试是否检查了其中一个,而未检查另一个.完成以下操作的最简单方法是什么:

Basically, I want to write an if statement and test if one of them is checked and another is NOT checked. What's the easiest way to accomplish the following:

if ( $("#checkSurfaceEnvironment-1").attr('checked', true) &&
     $("#checkSurfaceEnvironment-2").is('**(NOT??)** :checked') ) {
        // do something
}

推荐答案

我使用的一种可靠方法是:

One reliable way I use is:

if($("#checkSurfaceEnvironment-1").prop('checked') == true){
    //do something
}

如果要遍历选中的元素,请使用父元素

If you want to iterate over checked elements use the parent element

$("#parentId").find("checkbox").each(function(){
    if ($(this).prop('checked')==true){ 
        //do something
    }
});

更多信息:

这很好用,因为所有复选框都有一个选中的属性,用于存储复选框的实际状态.如果希望,您可以检查页面并尝试选中和取消选中复选框,那么您会注意到属性"checked"(如果存在)将保持不变.此属性仅表示复选框的初始状态,而不表示当前状态.当前状态存储在该复选框的dom元素选中的属性中.

This works well because all checkboxes have a property checked which stores the actual state of the checkbox. If you wish you can inspect the page and try to check and uncheck a checkbox, and you will notice the attribute "checked" (if present) will remain the same. This attribute only represents the initial state of the checkbox, and not the current state. The current state is stored in the property checked of the dom element for that checkbox.

请参见 HTML中的属性和属性

这篇关于jQuery:测试是否未选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆