jQuery复选框事件为何无法触发?

4

我有一个带有复选框的页面,其中一个是“全选”按钮。因此,当用户点击“全选”时,它会选中所有其他框,当单击另一个框时,它会取消选择全部。以下是代码。

          $(document).ready(function(event){   
                 //alert('wtf');
            $('#mailSubscribeAll').click(function(event){
                 //alert('wtf');
                $('.mailingCheckbox').attr('checked','checked');
            });             

            $('.mailingCheckbox').bind('click',function(event){
                //alert('wtf');
                $('#mailSubscribeAll').removeAttr('checked');
            });

        });

我的页面可以成功加载jQuery库,第一个警告框也能弹出。但是点击事件没有任何反应。我已经仔细检查了HTML代码。

我是否使用了错误的jQuery事件,或者我的页面中可能存在与jQuery不兼容的其他JavaScript代码?

HTML代码片段:

    <tr>
    <td class="CBT3" colspan="3" height="29">
        <input type="checkbox" class="mailingCheckbox" id="mailNewsAlerts"    value="1" {if $smarty.session.profile.mailNewsAlerts}checked{/if} onclick="subscribeMarkProfile()">
        <label for="mailNewsAlerts"><b>News Alerts</b> - <cite>The latest breaking news from XXXXXXX</cite></label>
    </td>
</tr>    
<tr>
    <td class="CBT3" colspan="3" height="29">
        <input type="checkbox" id="mailSubscribeAll"    value="1" {if $smarty.session.profile.mailSubscribeAll}checked{/if} >
        <label for="mailSubscribeAll"><b>Subscribe me to all XXXXX newsletters!</b> </label>
    </td>
</tr>    

我还要添加的是,页面上复选框部分在页面加载时不可见,但在HTML中存在。当点击按钮后,我会显示该区域,但是在页面加载时,这些复选框一开始是不可见的。


有HTML代码片段可用吗? - Jerod Venema
新增了,这段代码一团糟,全都在表格里,哎呀我粘贴的是Smarty模板代码,而不是渲染后的HTML,但我检查过了,它可以正常渲染。 - tkotitan
另外,从技术上讲,如果这很重要的话,我的输入字段不在<form>标签中。 - tkotitan
点击不等于更改。通常有注释指出错误,比如在答案中给出错误建议的情况,例如建议使用click事件的答案:https://dev59.com/hnA75IYBdhLWcg3wKlqM#3442342。 - basic6
3个回答

1

以下代码对我来说可以正常工作:

<div>
  <input type="checkbox" id="mailSubscribeAll"/>
  <input type="checkbox" class="mailingCheckbox"/>
  <input type="checkbox" class="mailingCheckbox"/>
</div>

<script type="text/javascript">
  $(document).ready(function(event){   
    $('#mailSubscribeAll').click(function(){
      $('.mailingCheckbox').attr('checked','checked');
    });             
    $('.mailingCheckbox').click(function(){
      $('#mailSubscribeAll').removeAttr('checked');
    });
  });    
</script>

这能解决你的问题吗?


1
 $("input:checkbox #mailSubscribeAll").click(function(event){
   $('.mailingCheckbox').attr('checked','checked');
});  

看起来不错,但你能试试这段代码吗?


1
当您以编程方式更改复选框的状态时,您还必须检查事件change,因为单击事件并不总是触发。
$('.mailingCheckbox').bind('change', ...

由于您有两个函数,应该这样做:

function changeMailingCheckbox(...) { ... }
$('.mailingCheckbox').bind('change', changeMailingCheckbox)
$('.mailingCheckbox').bind('click', changeMailingCheckbox)

谢谢你的建议,我试了一下,但没有成功。我认为我的页面表格太混乱了,可能导致 jQuery 无法正常工作? - tkotitan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接