简体   繁体   中英

Insert text into an undetermined number of spans, For Loop Javascript

I have this span:

<span class="spanComments" cols="100" rows="5"></span>

being called by this :

<a href="#" rel="@currentShowing.ShowingGUID" class="showComments noprint" id="comments-sendlink" onclick="showComments()">View Comments</a>

using this function:

    function showComments() {
    for (var arg = 0; arg < arg.length; ++arg) {
        var arr = arguments[arg];
        for (var i = 0; i < arr.length; ++ i) {
            document.getElementById("spanComments").innerHTML = "This is comment #" + arr[i];
        }
    }
}

I used this SO question as my basis to no avail: JavaScript For Loop

I'm not getting my span to populate anything (it's completely empty) I have tested my showComments() and it works (prior to me entering the for loop) and it worked.

I'm new to JavaScript, so I wouldn't be surprised if it were something really easy that I might have overlooked. Thanks in advance.

Couple problems here: you are iterating over args before it is defined, arguments should be what you are iterating over in your top most loop. Additionally, you are overwriting the same item each time (I assume there are multiple spanComments ). I suggest changing to class="spanComments" and using the following:

function showComments() {
   var comments = document.querySelectorAll(".spanComments");
   for(var i = 0; i < comments.length; i++) {
      comments[i].innerHTML = "This is comment #" + i;
   }
}

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