Javascript event repeats itself in other Ids

Asked

Viewed 35 times

0

I wanted to make a Javascript if repeated in other screen components, in this example I am passing I did a foreach and inside it I put my javascript. the intention is that it repeated itself 10 times, but it only works once. Is there something similar to what I’m trying to do? the intention is that the Ids were varied at each foreach, but I put the +i or not it always runs in a single div.

@for (var i = 10; i < 21; i++)
{
    <p>A script on this page starts this clock:</p>

    <p id="demo+@i"></p>

    <script>
        var myVar = setInterval(myTimer, 1000);

        function myTimer() {
            var d = new Date();
            document.getElementById("demo"+@i).innerHTML = d.toLocaleTimeString();
        }
    </script>
}

1 answer

1


Fabio, your problem is in the name of tag <p>, she’s getting something like demo+10 rather than demo10.

The second point, you’re declaring myTimer on the global scope, so with each interaction of yours, you’re overwriting it, so one way out is to make a IIFE.

@for (var i = 10; i < 21; i++)
{
    <p>A script on this page starts this clock:</p>
    <p id="demo@i"></p>

    <script>
        var myVar = (function () {
            function myTimer() {
                var d = new Date();
                document.getElementById("demo@i").innerHTML = d.toLocaleTimeString();
            }
            return setInterval(myTimer, 1000);
        })();
    </script>
}

remembering that this approach is far from ideal, the best to do would be to put a class to the tag

and have a single setInterval.

@for (var i = 10; i < 21; i++)
{
    <p>A script on this page starts this clock:</p>
    <p id="demo@i" class="demo"></p>    
}

<script>
    var demos = document.querySelectorAll(".demo");
    function myTimer() {
        var d = new Date();
        for (i = 0; i < demos.length; i++) {
          demos[i].innerHTML = d.toLocaleTimeString();;
        }
    }
    var myVar = setInterval(myTimer, 1000);
</script>

  • Boy, thank you very much, that’s exactly what I was trying to understand, it will help me a lot. thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.