jquery中each函数的bug

  • A+
所属分类:jquery

由于项目中checkbox的勾中效果是用css来实现的,这样一来从后台传回来的初期值check为true,但是看起来是没有被勾中的。所以需要在初值的jquery里遍历所有checkbox,如果勾中,则加上相应的css。

但是以下代码却无效果。

$(".checkbox__button").each(function(){
  if ($(this).checked) {
    $(this).parent().addClass('checkbox--checked');
    $(this).parent().addClass('checkbox__button--focus');
  }
});

debug分析发现,在each中,$(this)对象居然不是<input type="checkbox"这一层,而$(this)[0]才是。但是$(".checkbox__button")确实是<input type="checkbox"的class。

换成下面写法则OK。

$(".checkbox__button").each(function(index,element){
  if (element.checked) {
    $(this).parent().addClass('checkbox--checked');
    $(this).parent().addClass('checkbox__button--focus');
  }
});

也就是说用each函数的内置参数element就可以。。取父元素时用$(this)又可以。。按理说这里用$(this)和element应该是一样的,感觉是jquery的一个bug。

如果谁知道具体原因,请指教。

ZPY

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: