简体   繁体   中英

Change innerHTML of clicked element javascript

I have 4 cards and I want to change the text of its element on click, below is my html:

<tr>
      <td class="card">down</td>
      <td class="card">down</td>
    </tr>
    <tr>
      <td class="card">down</td>
      <td class="card">down</td>
    </tr>

So if I click on any card its text should be up and others should be down. I am able to change the text of clicked card but how I can change back other cards value to down? Below is my JS

var cards = document.getElementsByClassName('card');

            for (var i = 0; i < cards.length; i++) {
                cards[i].onclick = function(target) {
                    this.innerHTML = 'up';
                }
            }

You could turn all cards down and then set this card up OR
you could create a variable which stores the last card which was clicked and then only turn that card down and the clicked up .
This way you won't have to use a loop inside the event handler.

var cards = document.getElementsByClassName('card');
var k;

            for (var i = 0; i < cards.length; i++) {
                cards[i].onclick = function(target) {
                    if(k) {
                        k.innerHTML='down';
                    }
                    this.innerHTML='up';
                    k=this;
                }
            }

You can do it like:

var cards = document.getElementsByClassName('card');
for (var i = 0; i < cards.length; i++) {
  cards[i].onclick = function(target) {
    // Turn the 'cards' into an array and loop over it.
    [].forEach.call(cards, function(card) { 
      card.innerHTML = "down" 
    });
    this.innerHTML = "up";
  }
}

This will loop over all the cards and return their values to "down" .

Fiddle

Demo below

 var cards = document.getElementsByClassName('card'); for (var i = 0; i < cards.length; i++) { cards[i].onclick = function(target) { [].forEach.call(cards, function(card) { card.innerHTML = "down" }); this.innerHTML = "up"; } } 
 <table> <tr> <td class="card">down</td> <td class="card">down</td> </tr> <tr> <td class="card">down</td> <td class="card">down</td> </tr> </table> 

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