简体   繁体   中英

How to turn onclick function to default text when another element is clicked

I am using an onClick method to change the text of an element, I have a 3x3 grid layout and the below is an example of one square in this grid. Currently if I click each square they will all change their text but I would like to return to the default text located in the p tag when another element is clicked.

onClick="changeText('Some text blah blah blah.','home-grid-one-two')" 
<p style="text-align: center;">Measurable</p>

At the moment this is the JavaScript function which the onClick calls

function changeText(text, ele)


     { 
            var display = document.getElementById(ele);
            display.innerHTML = "";
            display.style.textAlign = "center";
            display.style.fontSize = "1em";
            display.innerHTML = text;
        }

You can store the previous values, then restore them when clicking another element.

var previousElement = null;
var previousText = "";

function changeText(text, ele) { 
  //restore previous values
  if(previousElement) {
    previousElement.innerHTML = previousText;
  }

  //store the values
  previousElement = document.getElementById(ele);
  previousText = previousElement.innerHTML;

  previousElement.innerHTML = ""; //this isn't required
  previousElement.style.textAlign = "center";
  previousElement.style.fontSize = "1em";
  previousElement.innerHTML = text;
}

EDIT: With the updated question, you asked about using the value from the p tag. You could do that.

I would give the p tag an id, like "#previousText". Then update the changeText() method to:

var previousElement = null;

function changeText(text, ele) { 
  var previousText = document.getElementById("previousText");

  //restore previous values
  if(previousElement) {
    previousElement.innerHTML = previousText.innerHTML;
  }

  //store the values
  previousElement = document.getElementById(ele);
  previousText.innerHTML = previousElement.innerHTML;

  previousElement.innerHTML = ""; //this isn't required
  previousElement.style.textAlign = "center";
  previousElement.style.fontSize = "1em";
  previousElement.innerHTML = text;
}

If you've designed it such that there's a pattern to the IDs of all the divs you want to control like this (say they all begin with "home-grid"), then you could do something like

$("[id=^home-grid]").innerHTML=<whatever your default text is>;

to return all of them to the default text, then change the one you've clicked to the text you want. If all of them have different default texts you might have to do something slightly more complex, but the theory of the method would be the same.

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