Как применить файлы cookie localStorage или javascript в моей программе?

0

Я изучил некоторые сайты о localStorage и куки файлы javascript, и я попытался применить его, но не повезло, он всегда не работал. Я хочу применить куки localStorage или javascript к моему назначению. Простой вопрос о резервировании. Я хочу, чтобы браузер помнил изменения, которые я сделал в браузере.

Javascript:

<script type="text/javascript">
        var availableSlot1 = 5;
        var reduceSlot1 = function(valueToDeduct1){
            availableSlot1 = availableSlot1 - valueToDeduct1;
            document.getElementById('ite164').innerHTML = availableSlot1;
            if (availableSlot1 == 0){
                document.getElementById('ite164').innerHTML = "FULL";
                document.getElementById("ite164").style.color = "red";
                document.getElementById("number1").style.color = "red";
                document.getElementById("subject1").style.color = "red";
                document.getElementById("code1").style.color = "red";
                document.getElementById("units1").style.color = "red";
                document.getElementById("prof1").style.color = "red";
                document.getElementById("1").style.display = "none";
            }
        };
        var availableSlot2 = 5;
        var reduceSlot2 = function(valueToDeduct2){
            availableSlot2 = availableSlot2 - valueToDeduct2;
            document.getElementById('phi001').innerHTML = availableSlot2;
            if (availableSlot2 == 0){
                document.getElementById('phi001').innerHTML = "FULL";
                document.getElementById("phi001").style.color = "red";
                document.getElementById("number2").style.color = "red";
                document.getElementById("subject2").style.color = "red";
                document.getElementById("code2").style.color = "red";
                document.getElementById("units2").style.color = "red";
                document.getElementById("prof2").style.color = "red";
                document.getElementById("2").style.display = "none";
            }
        };
        var availableSlot3 = 5;
        var reduceSlot3 = function(valueToDeduct3){
            availableSlot3 = availableSlot3 - valueToDeduct3;
            document.getElementById('ite165').innerHTML = availableSlot3;
            if (availableSlot3 == 0){
                document.getElementById('ite165').innerHTML = "FULL";
                document.getElementById("ite165").style.color = "red";
                document.getElementById("number3").style.color = "red";
                document.getElementById("subject3").style.color = "red";
                document.getElementById("code3").style.color = "red";
                document.getElementById("units3").style.color = "red";
                document.getElementById("prof3").style.color = "red";
                document.getElementById("3").style.display = "none";
            }
        };
        var availableSlot4 = 5;
        var reduceSlot4 = function(valueToDeduct4){
            availableSlot4 = availableSlot4 - valueToDeduct4;
            document.getElementById('ite048').innerHTML = availableSlot4;
            if (availableSlot4 == 0){
                document.getElementById('ite048').innerHTML = "FULL";
                document.getElementById("ite048").style.color = "red";
                document.getElementById("number4").style.color = "red";
                document.getElementById("subject4").style.color = "red";
                document.getElementById("code4").style.color = "red";
                document.getElementById("units4").style.color = "red";
                document.getElementById("prof4").style.color = "red";
                document.getElementById("4").style.display = "none";
            }
        };
        var availableSlot5 = 5;
        var reduceSlot5 = function(valueToDeduct5){
            availableSlot5 = availableSlot5 - valueToDeduct5;
            document.getElementById('ite136').innerHTML = availableSlot5;
            if (availableSlot5 == 0){
                document.getElementById('ite136').innerHTML = "FULL";
                document.getElementById("ite136").style.color = "red";
                document.getElementById("number5").style.color = "red";
                document.getElementById("subject5").style.color = "red";
                document.getElementById("code5").style.color = "red";
                document.getElementById("units5").style.color = "red";
                document.getElementById("prof5").style.color = "red";
                document.getElementById("5").style.display = "none";
            }
        };

Jquery:

<script>
$(document).ready(function(){
            $("#button1").hide();
            $("#button2").hide();
            $("#button3").hide();
            $("#button4").hide();
            $("#button5").hide();
            $("#button6").hide();
            $("#button7").hide();
            $("#1").click(function(){
                $("#button1").show();
                $("#button1").fadeIn(1000);
                $("#button2").hide();
                $("#button3").hide();
                $("#button4").hide();
                $("#button5").hide();
                $("#button6").hide();
                $("#button7").hide();
                    $("#button1").click(function() {
                        $("#button1").hide();
                    });
              });
              $("#2").click(function(){
                $("#button1").hide();
                $("#button2").show();
                $("#button2").fadeIn(1000);
                $("#button3").hide();
                $("#button4").hide();
                $("#button5").hide();
                $("#button6").hide();
                $("#button7").hide();
                    $("#button2").click(function() {
                        $("#button2").hide();
                    });
              });
              $("#3").click(function(){
                $("#button1").hide();
                $("#button2").hide();
                $("#button3").show();
                $("#button3").fadeIn(1000);
                $("#button4").hide();
                $("#button5").hide();
                $("#button6").hide();
                $("#button7").hide();
                    $("#button3").click(function() {
                        $("#button3").hide();
                    });
              });
              $("#4").click(function(){
                $("#button1").hide();
                $("#button2").hide();
                $("#button3").hide();
                $("#button4").show();
                $("#button4").fadeIn(1000);
                $("#button5").hide();
                $("#button6").hide();
                $("#button7").hide();
                    $("#button4").click(function() {
                        $("#button4").hide();
                    });
              });
              $("#5").click(function(){
                $("#button1").hide();
                $("#button2").hide();
                $("#button3").hide();
                $("#button4").hide();
                $("#button5").show();
                $("#button5").fadeIn(1000);
                $("#button6").hide();
                $("#button7").hide();
                    $("#button5").click(function() {
                        $("#button5").hide();
                    });
              });
              $("#6").click(function(){
                $("#button1").hide();
                $("#button2").hide();
                $("#button3").hide();
                $("#button4").hide();
                $("#button5").hide();
                $("#button6").show();
                $("#button6").fadeIn(1000);
                $("#button7").hide();
                    $("#button6").click(function() {
                        $("#button6").hide();
                    });
              });
              $("#7").click(function(){
                $("#button1").hide();
                $("#button2").hide();
                $("#button3").hide();
                $("#button4").hide();
                $("#button5").hide();
                $("#button6").hide();
                $("#button7").show();
                $("#button7").fadeIn(1000);
                    $("#button7").click(function() {
                        $("#button7").hide();
                    });
              });
        });
</script>

HTML:

<table border="1" width="700px">
        <tr>
            <th>#</th>
            <th>Subjects</th>
            <th>Subject Code</th>
            <th>Units</th>
            <th>Instructor</th>
            <th>Available Slots</th>
        </tr>
        <tr>
            <td class="center" id="number1">1</td>
            <td id="subject1">Data Comm. Systems & Networking</td>
            <td class="center" id="code1">ITE164</td>
            <td class="center" id="units1">3.0</td>
            <td id="prof1">Quinito, Floreto Jr. R.</td>
            <td style="text-align: center;"><span id="ite164">5</span></td>
        </tr>
        <tr>
            <td class="center" id="number2">2</td>
            <td id="subject2">Introduction to Philosophy and Logic</td>
            <td class="center" id="code2">PHI001</td>
            <td class="center" id="units2">3.0</td>
            <td id="prof2">Chiong, Isidro R.</td>
            <td style="text-align: center;"><span id="phi001">5</span></td>
        </tr>
        <tr>
            <td class="center" id="number3">3</td>
            <td id="subject3">Basic Finance & Acctg. Principles for IT</td>
            <td class="center" id="code3">ITE165</td>
            <td class="center" id="units3">3.0</td>
            <td id="prof3">Cadelinia, Godofredo B.</td>
            <td style="text-align: center;"><span id="ite165">5</span></td>
        </tr>
        <tr>
            <td class="center" id="number4">4</td>
            <td id="subject4">Discrete Structures</td>
            <td class="center" id="code4">ITE048</td>
            <td class="center" id="units4">3.0</td>
            <td id="prof4">Calibara, Eunelfa Regie F.</td>
            <td style="text-align: center;"><span id="ite048">5</span></td>
        </tr>
        <tr>
            <td class="center" id="number5">5</td>
            <td id="subject5">Web Page Design</td>
            <td class="center" id="code5">ITE136</td>
            <td class="center" id="units5">3.0</td>
            <td id="prof5">Pequiro, Chemby Mae S.</td>
            <td style="text-align: center;"><span id="ite136">5</span></td>
        </tr>
        <tr>
            <td class="center" id="number6">6</td>
            <td id="subject6">Systems Analysis and Design</td>
            <td class="center" id="code6">ITE062</td>
            <td class="center" id="units6">3.0</td>
            <td id="prof6">Galudo, Darwin M.</td>
            <td style="text-align: center;"><span id="ite062">5</span></td>
        </tr>
        <tr>
            <td class="center" id="number7">7</td>
            <td id="subject7">Operating System</td>
            <td class="center" id="code7">ITE076</td>
            <td class="center" id="units7">3.0</td>
            <td id="prof7">Lagala, Glenn T.</td>
            <td style="text-align: center;"><span id="ite076">5</span></td>
        </tr>
    </table>
    <div id="combobox">
        <span style="color: white;">Select a subject to reserve:</span>
        <select>
          <option id="1" value="ITE164">Data Comm. Systems & Networking (ITE164)</option>
          <option id="2" value="PHI001">Introduction to Philosophy and Logic (PHI001)</option>
          <option id="3" value="ITE165">Basic Finance & Acctg. Principles for IT (ITE165)</option>
          <option id="4" value="ITE048">Discrete Structures (ITE048)</option>
          <option id="5" value="ITE136">Web Page Design (ITE136)</option>
          <option id="6" value="ITE062">Systems Analysis and Design (ITE062)</option>
           <option id="7" value="ITE076">Operating System (ITE076)</option>
        </select> 
         <a href="javascript:reduceSlot1(1)" id="button1"><input type="button" value="Reserve"></a>
         <a href="javascript:reduceSlot2(1)" id="button2"><input type="button" value="Reserve"></a>
         <a href="javascript:reduceSlot3(1)" id="button3"><input type="button" value="Reserve"></a>
         <a href="javascript:reduceSlot4(1)" id="button4"><input type="button" value="Reserve"></a>
         <a href="javascript:reduceSlot5(1)" id="button5"><input type="button" value="Reserve"></a>
         <a href="javascript:reduceSlot6(1)" id="button6"><input type="button" value="Reserve"></a>
         <a href="javascript:reduceSlot7(1)" id="button7"><input type="button" value="Reserve"></a>
    </div>

Прошу прощения за очень грязный код, я все еще новичок. Вы можете мне помочь?

  • 2
    Подумайте о том, чтобы придать общий класс сходным элементам, чтобы вы могли просто скрыть их одним селектором, а не иметь 20 операторов скрытия для идентификаторов
  • 0
    @tymeJV ах хорошо, я не всегда использую class я постараюсь сделать его короче
Показать ещё 3 комментария
Теги:

3 ответа

2

Локальное хранилище будет работать на то, что вы пытаетесь сделать лучше, чем файлы cookie. В принципе, в окне, называемом localStorage, есть массив-подобный объект. Вы можете использовать его для хранения только произвольных строк. Подобно:

window.localStorage["button1_is_showing"] = true;

или:

window.localstorage.button1_is_showing = true;

true логическое значение будет преобразовано в строку "true". Чтобы включить его в логическое снова через некоторое время:

var b1showing;
if (window.localStorage.button1_is_showing == "true") {
    b1showing = true;
}
else {
    b1showing = false;
}

Вы также можете использовать браузер JSON для этого:

var b1showing = JSON.parse(window.localStorage.button1_is_showing);

Но имейте в виду, что у этого нет сильной поддержки браузера: http://caniuse.com/#search=JSON

Независимо от того, какие строки вы храните в localStorage, они останутся там до тех пор, пока браузер не очистит файлы cookie или пока вы не удалите что-то вроде этого:

delete window.localStorage.b1showing;

В вашем конкретном примере: каждый раз, когда пользователь нажимает кнопку, создайте один объект в localStorage для каждой кнопки, который будет хранить состояние кнопок. Затем, когда страница загружается (в вашем готовом событии), пройдите через локальную проверку, чтобы проверить, что там есть, и скрыть/показать кнопки в зависимости от этого.

Замечание: использование классов вместо 7 разных идентификаторов гораздо более гибкое, читаемое и быстрое.

EDIT: Еще один отличный источник: http://diveintohtml5.info/storage.html

Тонны больше информации здесь: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

  • 0
    +1. Вы можете упростить обработку строк путем (де) сериализации в JSON: stackoverflow.com/questions/15983170/…
  • 0
    @TimMedora Это был мой план, но объект JSON не поддерживается некоторыми старыми браузерами. Однако добавлю это к ответу.
Показать ещё 1 комментарий
1

вы можете использовать что-то вроде этого..

<table id="slotTable" border="1" width="700px">
        <tr>
            <th>#</th>
            <th>Subjects</th>
            <th>Subject Code</th>
            <th>Units</th>
            <th>Instructor</th>
            <th>Available Slots</th>
        </tr>
        <tr  >
            <td class="center" id="number1">1</td>
            <td id="subject1">Data Comm. Systems & Networking</td>
            <td class="center" id="code1">ITE164</td>
            <td class="center" id="units1">3.0</td>
            <td id="prof1">Quinito, Floreto Jr. R.</td>
            <td style="text-align: center;">5</td>
        </tr>
        <tr>
            <td class="center" id="number2">2</td>
            <td id="subject2">Introduction to Philosophy and Logic</td>
            <td class="center" id="code2">PHI001</td>
            <td class="center" id="units2">3.0</td>
            <td id="prof2">Chiong, Isidro R.</td>
            <td style="text-align: center;">5</td>
        </tr>
        <tr>
            <td class="center" id="number3">3</td>
            <td id="subject3">Basic Finance & Acctg. Principles for IT</td>
            <td class="center" id="code3">ITE165</td>
            <td class="center" id="units3">3.0</td>
            <td id="prof3">Cadelinia, Godofredo B.</td>
            <td style="text-align: center;">5</td>
        </tr>
        <tr>
            <td class="center" id="number4">4</td>
            <td id="subject4">Discrete Structures</td>
            <td class="center" id="code4">ITE048</td>
            <td class="center" id="units4">3.0</td>
            <td id="prof4">Calibara, Eunelfa Regie F.</td>
            <td style="text-align: center;">5</td>
        </tr>
        <tr>
            <td class="center" id="number5">5</td>
            <td id="subject5">Web Page Design</td>
            <td class="center" id="code5">ITE136</td>
            <td class="center" id="units5">3.0</td>
            <td id="prof5">Pequiro, Chemby Mae S.</td>
            <td style="text-align: center;">5</td>
        </tr>
        <tr>
            <td class="center" id="number6">6</td>
            <td id="subject6">Systems Analysis and Design</td>
            <td class="center" id="code6">ITE062</td>
            <td class="center" id="units6">3.0</td>
            <td id="prof6">Galudo, Darwin M.</td>
            <td style="text-align: center;">5</td>
        </tr>
        <tr>
            <td class="center" id="number7">7</td>
            <td id="subject7">Operating System</td>
            <td class="center" id="code7">ITE076</td>
            <td class="center" id="units7">3.0</td>
            <td id="prof7">Lagala, Glenn T.</td>
            <td style="text-align: center;"><span id="ite076">5</span></td>
        </tr>
    </table>
    <div id="combobox">
        <span style="color: white;">Select a subject to reserve:</span>

        <select onchange="updateCurrentSlot(this.value)" >
          <option id="1" value="ITE164">Data Comm. Systems & Networking (ITE164)</option>
          <option id="2" value="PHI001">Introduction to Philosophy and Logic (PHI001)</option>
          <option id="3" value="ITE165">Basic Finance & Acctg. Principles for IT (ITE165)</option>
          <option id="4" value="ITE048">Discrete Structures (ITE048)</option>
          <option id="5" value="ITE136">Web Page Design (ITE136)</option>
          <option id="6" value="ITE062">Systems Analysis and Design (ITE062)</option>
          <option id="7" value="ITE076">Operating System (ITE076)</option>
        </select> 

         <a href="javascript:reduceSlot(1)"  id="button"><input type="button" value="Reserve"></a>
    </div>

и скрипт..

<script>
    // the currentSlot holds which slot is being seleted..
var currentSlot = 0 ; 

// check if data is already stored in the localStorage.. if not create a new one..
if (!localStorage.slots) { 
var slots = [
{'slotId' : 0 , 'slotVal' : 'ITE164' ,'availableSlot' : 5 },
{'slotId' : 1 , 'slotVal' : 'PHI001' ,'availableSlot' : 5 },
{'slotId' : 2 , 'slotVal' : 'ITE165' ,'availableSlot' : 5 },
{'slotId' : 3 , 'slotVal' : 'ITE048' ,'availableSlot' : 5 },
{'slotId' : 4 , 'slotVal' : 'ITE136' ,'availableSlot' : 5 },
{'slotId' : 5 , 'slotVal' : 'ITE062' ,'availableSlot' : 5 },
{'slotId' : 6 , 'slotVal' : 'ITE076' ,'availableSlot' : 5 }
] ;
}

else if( localStorage.slots) {
$(document).ready(function () {

slots = JSON.parse(localStorage.slots) ;
// update the slots accordig to the locally stored data

$("#slotTable tr").each(function(index) {     
if(index >=1 ) { // index 0 will be <th> 

// as 6th child of tr contains available slot.. 
$(this).find(':nth-child(6)').text(slots[index-1].availableSlot) ;

// checking if slots are full.. 
if(slots[index-1].availableSlot === 0 ) { $(this).find('td').css({'color' : 'red'}) ;
$(this).find(':nth-child(6)').text("Full") ;
}
}

});  
}) ;
}


// function to reduce the current selected slot.. 
function reduceSlot(reduceAmt) {

// if availableSlot is 1.. and is reduced.. it will be full.. 
if (slots[currentSlot].availableSlot == 1 ) {

// setting the requred stuff.. 
$("#slotTable tr").each(function(index) { 
if(index == currentSlot+1) { 
$(this).find('td').css({'color' : 'red'});
$(this).find(':nth-child(6)').text("Full") ; 
slots[currentSlot].availableSlot = 0 ;
}
});
}

// we have to reduce slot and update our 'slots' variable as well as the table data
else if (slots[currentSlot].availableSlot > 1) { 
slots[currentSlot].availableSlot = slots[currentSlot].availableSlot - reduceAmt ;
$("#slotTable tr").each(function(index) { 
if(index == currentSlot+ 1) $(this).find(':nth-child(6)').text(slots[currentSlot].availableSlot) ; 
}); 

}

// save data in localStorage
localStorage.slots = JSON.stringify(slots) ;

}

// when the option in select changes..  we have to update our currentSlot variable.
function updateCurrentSlot(sVal) { 
for(i=0;i<slots.length;i++) {
if(slots[i].slotVal === sVal) currentSlot = slots[i].slotId ;
}
}

</script>
  • 0
    все в порядке, я спешу, потому что крайний срок моего назначения - завтра, а чего не хватает, - localStorage. Спасибо.
  • 0
    ох .. ммм .. просто спрашиваю ... работает ли скрипт ??
Показать ещё 3 комментария
0

Во-первых, на событии есть событие onclick.

+ Изменить

$("#1").click(function(){...

в

$("#select_id").change(function() {...

См. Примеры здесь, чтобы узнать больше.

Поскольку вы уже используете jquery, возможно, было бы проще использовать куки jquery cookie - https://github.com/carhartl/jquery-cookie

$.cookie("test", 1); $.removeCookie("test");

Если вы не хотите использовать плагин, посмотрите на этот режим quirksmode

Посмотрите на другой ответ, если вы хотите использовать localstorage :)

Ура !!

  • 0
    возможно я должен использовать плагин jquery cookies, это кажется легким, потому что я спешу
  • 0
    ты можешь сделать код для меня? пожалуйста

Ещё вопросы

Сообщество Overcoder
Наверх
Меню