Suppose I have some number on the page, and I want it to decrease every second by 1 and, when it is 0, update the village. (A standard counter with a display in a specific location) A number is assigned to any variable. (Perhaps this is just for you, but I am not familiar with JS, so I ask for your help) I will derive the number using PHP
2 answers
<script type="text/javascript"> onload = function(){ // инициализируем интервал setInterval(function(){ // функция будет вызываться каждую секунду // выбираем наш "счетчик" див var counter = document.getElementById("counter"); // получаем целочисленное значение его HTML'я var counterValue = parseInt(counter.innerHTML); if(counterValue) { // если оно не 0 ( т.е. не является false ) --counterValue; // уменьшаем на единицу counter.innerHTML = counterValue; // записываем в элемент } else { // в противном случае document.location.href = ''; // перезагружаем страницу } }, 1000); } </script> <div id="counter">100</div> <!-- тут естественно можешь выводить любое int(>0) значение -->
|
For example, the initial value of the counter was derived by means of pkhp like this:
<div id="counter"><?php echo $init_count; ?></div>
Then in javascript:
var Counter = (function(){ var private = { start : 0, timer : 0, interval : 1000, value : 0, // значения, которые можно изменить в клиентском коде: elemId : 'counter', // значение по умолчанию destination : 'http://yandex.ru', // значение по умолчанию }, public = { init : function(options){ if ( options.hasOwnProperty('destination') ) { private.destination = options.destination; } if ( options.hasOwnProperty('elemId') ) { private.elemId = options.elemId; } private.elem = document.getElementById(private.elemId); // начальное значение if ( options.hasOwnProperty('start') ) { private.start = options.start; private.elem.innerHTML = private.start; } else { private.start = Number(private.elem.innerHTML) } // текущее значение равно начальному private.value = private.start; return public; }, go : function() { private.timer = window.setInterval(function(){ if ( private.value ) { public.countDown(); } else { public.action(); } }, private.interval) return public; }, countDown : function(){ private.elem.innerHTML = --private.value; }, action : function(){ document.location.href = private.destination; } }; return public; })(); // Обработчик написан, его можно вынести в отдельный файл // а ниже показано как его вызывать, использовать Counter.init({ elemId : 'counter', destination : 'http://google.com' }).go();
- onewhy such complexity (private, public ...)? 1. This will not only add brakes, but also memory eats ... 2. According to the standard, such words are reserved 3. Versatility of the code -> 0 - timka_s
- @timka_s - 100% solidarity ... @ Innuendo108 - have you heard about kiss ? And I will add about memory - eating from scratch ... - Zowie
- Does not add brakes, run in the profile in firebug. This is called the JavaScript Module Pattern, only in the original version all methods are not divided into public and private. and the separation makes it more convenient. I am used to almost any task of writing as a module, this adds extensibility. (although of course it is unlikely that a simple counter will grow into something, but still) Reserved words - yes, well, this does not prevent me from making such variables. @AlexWindHope, heard. If you write all your tasks as modules, you can reuse them anywhere. Have you heard about
DRY
? =) - Innuendo108 - @timka_s, @AlexWindHope, well, let's say the counter and the simple task, you do not need to expand it. But for example, later you will need to insert a similar counter into another page, with different elements and with a different logic of action. And then again in another. You will have to change the code, which is often almost equivalent to rewriting the code. In my case, one comment to the module, which indicates which methods it supports, and the module in a separate file. To embed it in a new page - just change the client code (call). All the logic of the counter can be put into a call, and everything will be flexible but. - Innuendo108
- I will only have to change the item ID. Even if I had to rewrite - 10 lines are not a panacea, I have nothing against modules, but definitely that you have written extremely unnecessarily and does not have practical meaning by definition. Nothing flexible did not notice, in my opinion very much the opposite. The fact that you are accustomed does not mean that it is good, about reserved words - it’s not so important, but for good it would be nice to take quotes. As for me, I don’t see any flexibility, and I don’t see any benefit from such complication, I didn’t see any harm, but I didn’t notice any good ... - Zowie
|