Javascript JQuery中的逻辑,使用复选框更新

Javascript JQuery中的逻辑,使用复选框更新,javascript,jquery,database,checkbox,logic,Javascript,Jquery,Database,Checkbox,Logic,我所有的代码都工作正常,我只是尝试扩展它以适应所有可能的情况,我知道一定有更好的方法可以做到这一点,但我认为我对javascript了解不够(我刚刚开始学习) 从本质上说,我试图调用数据库中的数据,基于该数据库,我的web应用程序上的复选框被选中。共有四个方框:“委员会”、“候选人”、“个人”、“意见” 我的代码是: if($('#committees').attr('checked')) { $.get("file.pl", { act: "near",

我所有的代码都工作正常,我只是尝试扩展它以适应所有可能的情况,我知道一定有更好的方法可以做到这一点,但我认为我对javascript了解不够(我刚刚开始学习)

从本质上说,我试图调用数据库中的数据,基于该数据库,我的web应用程序上的复选框被选中。共有四个方框:“委员会”、“候选人”、“个人”、“意见”

我的代码是:

if($('#committees').attr('checked')) {
    $.get("file.pl",
    {
       act: "near",
       format: "raw"
       what: "committees"
    }, NewData);
}
else {
    $.get("file.pl",
    {
       act: "near",
       format: "raw"
       what: ""
    }, NewData);
它只适用于committees复选框,(其他框的ID与“what”的表名匹配,并与上述名称匹配。我希望所有4个复选框都能使用此功能,而不必为每个可能的复选框组合生成大量嵌套语句

我知道我可以在“什么”类别中列出更多选项,如下所示:

$.get("file.pl",
        {
           act: "near",
           format: "raw"
           what: "committees, candidates, individuals, opinions"
        }, NewData);

这是可行的,但Idk如何动态更改该字符串以匹配选中的框。感谢您提供的任何帮助!

即使您说您的代码有效,我建议您使用
.is(':checked')
而不是
.attr('checked')

然后,您必须为每个复选框分配一个它们都将共享的类,例如
。checkbox
。您的代码是:

$('.checkbox').each(function() {
    if($(this).is(':checked')) {
        $.get("file.pl",
              {
                  act: "near",
                  format: "raw"
                  what: this.id
              }, NewData);
    } else {
        $.get("file.pl",
              {
                  act: "near",
                  format: "raw"
                  what: ""
              }, NewData);
    }    
});
更新

我现在意识到,这样的构造确实需要一个闭包才能工作:

$('.checkbox').each(function() {
    (function( that ) {
        if($(that).is(':checked')) {
            $.get("file.pl",
              {
                  act: "near",
                  format: "raw"
                  what: that.id
              }, NewData);
        } else {
            $.get("file.pl",
              {
                  act: "near",
                  format: "raw"
                  what: ""
              }, NewData);
        }
    })( this );   
});

你的意思是这样的吗?使用“this”关键字。
HTML


不幸的是,上述答案不太奏效。最终奏效的是:

var what string = "";
$('.filters').each(function() {
   if($(this).is(':checked')) {
      what string = whatstring+this.id+", ";
     }});
$.get("file.pl",
    {
       act: "near",
       format: "raw"
       what: whatstring
    }, NewData);

这不起作用,因为只有最后选择的数据通过了,我找到了答案,在下面发布了我的答案。谢谢你的回复。我也找到了。很高兴你找到了答案。如果你想一次处理所有的
复选框,更新的版本可能会有所帮助。
$(".file-pl").click(function(){
    var what = this.checked ? this.id : "";

    $.get("file.pl", {
    act: "near",
    format: "raw"
    what: what
    }, NewData);
});
var what string = "";
$('.filters').each(function() {
   if($(this).is(':checked')) {
      what string = whatstring+this.id+", ";
     }});
$.get("file.pl",
    {
       act: "near",
       format: "raw"
       what: whatstring
    }, NewData);