قم بإنشاء ملف تعريف ارتباط إذا لم يكن موجودًا (وفقط)

StackOverflow https://stackoverflow.com/questions/2824021

  •  26-09-2019
  •  | 
  •  

سؤال

أريد أن:

  1. تحقق لمعرفة ما إذا كان ملف تعريف الارتباط باسم "الاستعلام" موجود
  2. إذا كانت الإجابة بنعم ، فلا تفعل شيئًا
  3. إذا كان لا ، قم بإنشاء ملف تعريف ارتباط "استعلام" بقيمة 1

ملاحظة: أنا أستخدم jQuery 1.4.2 و jQuery Cookie Plugin.

هل لدى أي شخص أي اقتراحات حول كيف يمكنني القيام بذلك؟

هل كانت مفيدة؟

المحلول

if($.cookie('query') === null) { 
    $.cookie('query', '1', {expires:7, path:'/'});
}

بدلاً من ذلك ، يمكنك كتابة وظيفة غلاف لهذا:

jQuery.lazyCookie = function() {
   if(jQuery.cookie(arguments[0]) !== null) return;
   jQuery.cookie.apply(this, arguments);
};

ثم تحتاج فقط إلى كتابة هذا في رمز العميل الخاص بك:

$.lazyCookie('query', '1', {expires:7, path:'/'});

نصائح أخرى

هذه؟؟

$.cookie('query', '1'); //sets to 1...
$.cookie('query', null); // delete it...
$.cookie('query'); //gets the value....

if ($.cookie('query') == null){ //Check to see if a cookie with name of "query" exists
  $.cookie('query', '1'); //If not create a cookie "query" with a value of 1.
} // If so nothing.

ماذا تريد اكثر؟؟

على غرار إجابة جاكوبس ولكني أفضل اختبار غير محدد.

if($.cookie('query') == undefined){
    $.cookie('query', 1, { expires: 1 });
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top