此代码现在的方式意味着如果警报数量增加,我必须手动添加代码。如何组合下面的代码进行自我调整以适应任意数量的警报。
// Alert session cookie starts here
$(document).ready(function(){
$('.alert-box').attr('id', function(i) {
return 'alert'+(i+1);
});
function closeBox(){
var closeBox = $('#alert1').remove();
// - Notice how we pass a function and get an integer
$.cookie('Box-closed', true, {path: '/'});
}
// - Simply checks the alert box above
if($.cookie('Box-closed')){
console.log('Closing the alert box automatically...');
closeBox();
}
// Close the box on click
$('#alert1 .alert-switch').click(function () {
closeBox();
});
function closeBox2(){
var closeBox2 = $('#alert2').remove();
// - Notice how we pass a function and get an integer
$.cookie('Box2-closed', true, {path: '/'});
}
// - Simply checks the alert box above
if($.cookie('Box2-closed')){
console.log('Closing the alert box automatically...');
closeBox2();
}
// Close the box on click
$('#alert2 .alert-switch').click(function () {
closeBox2();
});
function closeBox3(){
var closeBox3 = $('#alert3').remove();
// - Notice how we pass a function and get an integer
$.cookie('Box3-closed', true, {path: '/'});
}
// - Simply checks the alert box above
if($.cookie('Box3-closed')){
console.log('Closing the alert box automatically...');
closeBox3();
}
// Close the box on click
$('#alert3 .alert-switch').click(function () {
closeBox3();
});
});
我尝试了下面的方法,它打破了整个事情
// Alert session cookie starts here
jg(document).ready(function(){
jg('.alert-box').attr('id', function(i) {
return 'alert'+(i+1);
});
function closeAlert(){
var alert = jg('.alert-box:visible');
var alertId = alert.attr('id');
alert.remove();
jg.cookie('Alert-is-closed-'+alertId, true, {path: '/'});
//cookie name will be different for each alert:
// Alert-is-closed-0
// Alert-is-closed-1
// Alert-is-closed-2
// ...and so on...
}
if(jg.cookie('Alert-is-closed-' + jg('.alert-box:visible').attr('id'))){
console.log('Closing the alert box automatically.');
closeAlert();
}
// Close the box on click
jg('.alert-switch').click(function () {
closeAlert();
});
});