[jQ]jQuery显式操作Checkbox,并用数组存储关联值的方案
--------------------------------------------------------------------------
/**
* 显式选中清空Checkbox(jQuery代码)
*/ var obj = $(':checkbox');
obj.on('click',function(){ oThis = $(this); if(oThis.attr('selected') == 'selected'){ oThis.removeAttr('selected'); }else{ oThis.attr({'selected':true}); } });
/**
* 注:如果是点击按钮(不直接点击Checkbox)触发事件,先取消可见勾选,再清除显式的属性勾选
*
* 如:$(':checkbox').each(function(){
* if($(this).attr('selected') == 'selected')
* {
* $(this).attr('checked', false); //取消可见的勾选
* $(this).removeAttr('selected'); //取消显式的属性勾选
* }
* });
*/
/** * 显式将Checkbox和隐藏值存入数组(jQuery代码) * @黑眼诗人 <www.farwish.com> */ var info = {"discount" : {"discount_id" : [], "discount_lesson_id" : []}}; infoDiscountId = info['discount']['discount_id']; infoDisLessonId = info['discount']['discount_lesson_id']; $('input[name="discount_id"]').on('click', function(){ var oThis = $(this); if(oThis.attr('selected') == 'selected'){ oThis.removeAttr('selected'); $.each(infoDisLessonId, function(i, n){ if(infoDisLessonId[i] == oThis.prev('input').val()){ delete infoDisLessonId[i]; //唯一性删除 j = i; //对应DiscountId中的i } }); delete infoDiscountId[j]; console.log(info); }else{ oThis.attr({'selected':true}); infoDiscountId.push(oThis.val()); //数组新增元素 infoDisLessonId.push(oThis.prev('input').val()); //新增元素2 console.log(info); } });
/*存在问题:
* 1.删除infoDisLessonId[i]时,虽然元素分别在infoDiscountId 和 infoDisLessonId中,但如果碰到它们当中有相同值,此时都将删除,这是所不希望发生的。
* 2.使用delete infoDiscountId[i]此种形式的删除时,原数组长度不变,索引还在,只是当前infoDiscountId[i]值变为undefined。
*/
/**
* 解决例2当中的存在问题,更换数组格式储值(jQuery代码)
* @黑眼诗人 <www.farwish.com>
*/
var info = {"discount" : []};
infoDiscountId = info['discount'];
$('input[name="discount_id"]').on('click', function(){ var oThis = $(this); if(oThis.attr('selected') == 'selected'){ oThis.removeAttr('selected'); $.each(infoDiscountId, function(i, n){ if(infoDiscountId[i]['discount_id'] == oThis.val() && infoDiscountId[i]['discount_lesson_id'] == oThis.prev('input').val()) { //删除前进行唯一性判断,参考添加时的存储方式 infoDiscountId.splice(i, 1); //使用splice删除单个元素,代替delete } }); console.log(info); }else{ oThis.attr({'selected':true}); infoDiscountId.push({"discount_id":oThis.val()}); //push在数组末尾添加一对数组元素,discount_id var index = infoDiscountId.length - 1; //获得新增元素的索引 infoDiscountId[index]['discount_lesson_id'] = oThis.prev('input').val(); //在此索引下再增加一对数组元素,discount_lesson_id console.log(info); } });
/*
* 完美解决例2中存在的问题
*/
应用场景:当需要由多个表数据关联得到某一具体数值时,上例是一种解决的思路和方案。
Refer:jQuery操作checkbox的利弊