0

在这段 javascript 中,想法是在有人点击时向前计数,直到他们达到“5”;然后它应该回去。

count=0;
function remote(w) {
    count++;
    if (count < 5 ) {
        for (var i=1;i<=5;i++) {
            var g = document.getElementById("searchme").value = w+count;
        }
    }else if (count > 4) { 
        for (var i=5;i > 0;i--) {
            //alert(i);
            var q = document.getElementById("searchme").value = w+count;
        }
    }
}

但是,它仅在有警报时才有效。您如何将“i”值转换为表单?

哦,谢谢大家的快速回复。它促使我想出一些办法:

var f = 0;
var s = 0;
function upDown() {
    if (s < 5 && f==0){
        countUp('no.');
        if (s==5){f=1}
    }else if(s > 0 && f==1){
        countDown('no.');
        if (s==0){f=0}
    }
}

function countUp(w) {
    s++;
    var el = document.getElementById('box03').innerHTML = w+s;
}

function countDown(w) {
    s--;
    var el= document.getElementById('box03').innerHTML = w+s;
}
4

3 回答 3

1

All JavaScript (other than web workers) on the web is synchronous -- While your JS is running the browser can't do anything else - including painting. The reason you see an update when the alert dialog comes up is because the various mechanisms in a browser that make it work also require them to repaint the main window.

If you want to be able to show 1, 2, 3 .. etc you'll need to use a timeout.

于 2011-04-11T16:43:16.170 回答
1

One of the simplest solution would be to use innerHTML, both in implementation and logic:

JS

document.getElementById('logs').innerHTML+='Hello ';
document.getElementById('logs').innerHTML+='World ';
document.getElementById('logs').innerHTML+='!';

HTML

<div id="logs"></div>

UPDATE

Taking the code that you commented on my post and updating it a bit:

var max = 5;
var min = 0;
var cur = 0;
var dir = 1;

function pingPong() {
    cur+=dir;
    document.getElementById('box').innerHTML='No.'+cur;
    if(cur==max){dir=-1;return;}// ping
    if(cur==min){dir=1;return;}// pong
}
window.onclick=pingPong;

Example on jsfiddle

于 2011-04-11T16:43:32.637 回答
0

You can point a variable towards the document element you wish to update (eg searchme) and then assign the value of that object.

If the object is a form element (input) then you can use the .value parameter. If the object is a div/span or some other HTML element, you need to change the value of .innerHTML

//For DIV/SPAN etc:
var el=document.getElementById("divx");
el.innerHTML=i;

//For INPUT
var el=document.getElementById('inputx');
el.value=i;

NOTE without delays the element is just going to appear to hold the last value only (because it'll update too fast for you to observe)

于 2011-04-11T16:42:09.860 回答