2

我有一个关于 Jquery 和复选框的简单问题。我以前从未使用过 JQuery,但基本上我有一个复选框,当用户进入页面时,它默认设置为“选中”。我希望 jquery 检测到它已被检查,然后将触发一个单独的函数。

我只有在用户单击复选框时才能让它工作,但我不希望它这样做。所有这些都将在用户不触碰任何东西的情况下完成。

这是我不起作用的功能:

if ($('#discount:checked').val!== null) { changeprice(); };

先感谢您!

4

6 回答 6

2
$(document).ready(function(){
   if ($('#discount:checked').length > 0) { changeprice(); }
});
于 2010-11-17T20:06:17.080 回答
1

您可能希望在 DOM 实例化之前保存您的代码。幸运的是,jQuery 提供了一个很好的方法来做到这一点:

$(document).ready(function () {
    if ($('#discount:checked').val !== null)
    {
        changeprice();
    }
});

$(document).ready惯用语是在 jQuery 中页面加载后尽快使某些事情发生的标准方法。

于 2010-11-17T20:06:40.203 回答
0

jQuery val()方法需要像这样调用:

if ($('#discount:checked').val() !== "") { changeprice(); }; 

最重要的是,您应该使用$(document).ready()函数在页面加载时执行命令。

最后,使用选中的选择器会更容易。

$(document).ready(function () {
  if ($('#discount:checked').length) {  // if the discount checkbox is checked
    changeprice(); 
  }
});
于 2010-11-17T20:10:39.357 回答
0

我认为这就是你想要的:

if ($('#discount:checked').length == 1) { changeprice(); };
于 2010-11-17T20:07:19.220 回答
0
if ($('#discount').attr('checked')) changeprice();
于 2010-11-17T20:07:43.490 回答
0

可能您可以将复选框放在文档就绪方法中检查代码,

$(document).ready(
  function(){
     if($("#discount").is(':checked')) { changeprice();}
   }
);

问候, 贾坦

于 2010-11-17T20:08:05.920 回答