想要多次执行javascript而不刷新页面

时间:2013-09-13 16:37:36

标签: javascript html

我希望javascript可以执行多次,但它只是 执行一次。下面的代码完全正常,但在之后 点击两个按钮,我必须刷新页面才能使其正常工作 再次。请帮我解决这个问题。只是想执行它 很多次,我想,但没有刷新页面。

HTML:

<body> 
    <h1 class="head" id="h" onclick="change()">TEST PAGE</h1> 
        <form name="myform"> 
            <input name="horizontal" type="button" class="button1" value="Swap Horizontal" id="SH1" onclick="swaphorizontal()"> 
        </form> 
        <form name="myform1"> 
            <input name="vertical" type="button" class="button2" value="Swap Vertical" id="SV1" onclick="swapvertical()"> 
        </form> 
        <h2 class="mybox"></h2> 
        <h2 class="line1"></h2> 
        <h2 class="line2"></h2> 
        <h2 class="voidbutton1"></h2> 
        <h2 class="voidbutton2"></h2> 
</body>

JS:

<script>

    function swapvertical() {

        document.getElementById("SV1").style.top = "210px";

        document.getElementById("SH1").style.top = "414px";

    }
    function swaphorizontal() {

        document.getElementById("SV1").style.left = "386px";

        document.getElementById("SH1").style.left = "178px";

    }
</script>

1 个答案:

答案 0 :(得分:5)

它可能不止一次。问题是,您在JavaScript中所做的只是将值更改为静态值。

例如,在ogposition()中,您拨打document.getElementById("SH1").style.position = "absolute";下次拨打ogposition()时,SH1的位置已经是绝对的,所以再做一次不会改变任何内容,你不会注意到差异。

如果您想知道您的代码是否仅执行了一次或多次,请尝试在代码的可疑部分中添加console.log();语句。