javascript - 访问每个内部的原始对象

标签 javascript jquery

我想选中或取消选中以下代码对我有用的所有复选框

 $( '#chkboxall' ).live( 'change', function() {

                                objs=$(document).find('#chkbox');
                objs.each(function(){
                                $(this).attr( 'checked', $(this).is( ':checked' ) ? '' : 'checked' );
            });
                 });

但不是使用 $(this).is( ':checked' ) ? '' : 'checked' 我想获取我已检查的原始复选框的状态,即 $('#chkboxall' ) 的状态。我怎样才能在每个内部做到这一点?

克里什尼克

最佳答案

您可以缩短它,而无需 .each()这里(因为 .attr() 已经可以在集合中的每个元素上运行):

$('#chkboxall').live('change', function() {
  $(document).find('#chkbox').attr('checked', this.checked);
});

但是这是无效的,您有一个重复的 chkbox id 属性,该属性无效。给这些元素一个类,如下所示:

<input name="blah" class="chkbox" type="checkbox" />

然后使用 .class selector在您的代码中:

$('#chkboxall').live('change', function() {
  $('.chkbox').attr('checked', this.checked);
});

对于在不同情况下发现此问题的其他人,请获取对 .each() 内的“外部 this”的引用,只需设置一个变量,如下所示:

$('#chkboxall').live('change', function() {
  var thing = this;
  $('.chkbox').each(function(){
    //thing = the outer this, the #chkboxall element
  });
});

关于javascript - 访问每个内部的原始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4344586/

相关文章:

javascript - TypeError : this. state.student.map 不是一个函数

javascript - 如何从 iframe 打开弹出窗口

JQuery/Bootstrap : close and open the same modal to refresh the content, 是动态生成的

jquery - Rails 3 : jquery working to switch view with AJAX, 如何获得链接的焦点状态?

javascript - Vuejs 和 Drupal

javascript - jquery 查找并替换元素中的关键字

使用 "and"进行 javascript/jquery 复选框比较

javascript - 处理可能因多种原因而失败的 jQuery Promise

javascript - drupal_add_js() 正在工作,但 js 文件未执行

javascript - Facebook 的视频通话如何运作