简体   繁体   中英

JavaScript setInterval does not work with asp net

I want the label text run animate when i click to the button, but it's not work. If i use window.setInterval(afun, 150) outside the function, the label text will run automatic event i'm not click to the button. Where is my bug ?. Sorry for my bad English.

<form id="form1" runat="server">
    <div runat="server">

        <p id="demo" runat="server">
            <asp:Label runat="server" ID="label1">Animate Text</asp:Label>
            <asp:Button OnClientClick=" return afun();" Text="button" runat="server" />
        </p> 
    </div>
</form>

<script>

    function afun() {
        var element = document.getElementById('<%=label1.ClientID%>');
        var eText = element.innerHTML;
        var lengText = eText.length;
        window.setInterval(function () {
            eText = eText[lengText - 1] + eText.substring(0, lengText - 1);
            element.innerHTML = eText;
        },150);
    }
    //window.setInterval(afun, 150);
</script>

Your button is getting generated as a Submit button inside the form as following.

<input type="submit" name="ctl03" value="button" onclick=" return afun();">

You need to return false from your javascript to stop the default posting. Or you can also use plain HTML button in your code if you don't want your button to post.

Change your JavaScript function as following.

  function afun() {
        var element = document.getElementById('<%=label1.ClientID%>');
        var eText = element.innerHTML;
        var lengText = eText.length;
        window.setInterval(function () {
            eText = eText[lengText - 1] + eText.substring(0, lengText - 1);
            element.innerHTML = eText;
        }, 150);
        return false; //ADDED THIS LINE TO STOP FORM POSTING
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM