JavaScript event if it is repeated in other IDs

0

I wanted to make a JavaScript if it repeated in other components of the screen, in this example I'm passing I made a foreach and inside it I put my javascript. the intention is that it repeat itself 10 times, but it only works once. Is there something similar to what I'm trying to do? the intention is for the Ids to be varied at each foreach, but I putting the + i or not it always executes on 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>
}
    
asked by anonymous 21.11.2016 / 15:12

1 answer

1

Fabio, your problem is in the name of tag <p> , it is getting something like demo+10 instead of demo10 .

The second point, you are declaring myTimer in the global scope, so with each interaction of yours, you are overwriting it, so an output 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 thing to do would be to put a class into the

and have a unique 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>
    
21.11.2016 / 15:31