jquery 版本兼容性问题集合

来源:互联网 发布:淘宝客服图片图片发出 编辑:程序博客网 时间:2024/06/06 13:22


使用jquery的很多时候代码还是停留在过去1.2.6,1.4.2这些版本的API用法上面,其实之后的版本修改了很多,所以不小心会碰到很多坑,这里不停的更新列举下问题:

先看一段常规的1.4.2版本的代码:

$("#categoryAndItems div").delegate("input[type='checkbox']:eq(0)", 'click', function(){if ($(this).attr('checked')) {    console.log('c=' + $(this).prop('checked'));$(this).parent().parent().find("input[type='checkbox']:gt(0)").attr('checked', true);} else {$(this).parent().nextAll().find("input[type='checkbox']").attr('checked', false);}});

会发现这段代码在1.10这个版本中出现很多问题,首先attr这个属性在高版本的jquery中获取选择的状态,就会有各种问题;

其次在使用attr变为某个值之后,比如attr('checked', true);去看下html的源码,会发现checkbox的源码中多了checked="checked"

即使使用.attr('checked', false); 也无法修改其属性;

所以最后修改为:

        $("#categoryAndItems div").on('click', "input[type='checkbox']:eq(0)", function(){    console.log('c=' + $(this).prop('checked'));            if ($(this).prop('checked')) {    console.log('check=');$(this).parent().parent().find("input[type='checkbox']:gt(0)").prop('checked', true);} else {                $(this).parent().parent().find("input[type='checkbox']:gt(0)").prop('checked', false);}});