如何在达到限制后停止 sessionStorage 保存值

How to stop sessionStorage from saving the values after a limit is reached

我一直在想办法在单击 Add Another Worker 按钮时到达 max_fields 后如何阻止 sessionStorage 保存值?似乎在达到限制并再次单击按钮后,值不断添加到 sessionStorage 我想知道如何才能阻止这种情况发生。

这是我的 jsfiddle link https://jsfiddle.net/p2euLqbf/4/

HTML

<ul>
    <li>
        <div class="worker-container-last">
            <label class="worker-label">
                <select name="title[]" class="title">
                    <option value="Select a Title" selected="selected">Select a Title</option>
                    <option value="Boss">Boss</option>
                    <option value="Worker">Worker</option>
                    <option value="Manager">Manager</option>
                </select>
            </label>
        </div>
        <div class="add-more"></div>
        <div><a class="worker" title="" href="">Add Another Worker</a></div>
    </li>
</ul>

JQuery

var worker_record = [];
$(document).ready(function(){
    workerData();
    $('.worker').on('click', function(e){
        e.preventDefault();
        e.stopPropagation();

        var title = $('.title:first').val();            

        var someData = {title: title};
        worker_record.push(someData);

        sessionStorage.worker = JSON.stringify(worker_record);
        workerData();
    });

    function workerData(){
        var max_fields = 6;
        var x = 1;

        if(!(typeof sessionStorage.worker === 'undefined' || sessionStorage.worker.length<1)){
            worker_record = JSON.parse(sessionStorage.worker);
        }

        $('.add-more').empty();
        for(var i=0; i<worker_record.length; i++){
            if(x < max_fields){
                x++;
                var title = worker_record[i].title;

                var worker = '<select name="title[]" class="title title-options"><option value="Select a Title" selected="selected">Select a Title</option><option value="Boss">Boss</option><option value="Worker">Worker</option><option value="Manager">Manager</option></select>';

                $('.add-more').append(worker);
                $('.title:eq('+$('.title-options').length+')').val(title);
            }
        }

        $('.title:first').val('Select a Title');
    }
}); 

要设置限制,您可以这样做。

先设置一个变量

if (sessionStorage.getItem("limit") === null) {
    sessionStorage.setItem('limit', 0);
}

在每次迭代时增加 this 变量值并相应地设置限制检查 假设你要设置一个limit = 10然后,

if(sessionStorage.getItem('limit') <= 10 )
{
 var count = sessionStorage.getItem('limit');
     count++;

 sessionStorage.setItem('limit', count);

  //do whatever

}
else{

   alert("session limit reached!");
   return false;

 }

Working Demo