Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Changing the class of a div when clicking on it?

How can I change a div class name when clicking on it? Eg:

<div class="first_name" onclick="changeClass();" id="first_name"></div>

I want to change it as follows, when a user clicks on the div

<div class="second_name" onclick="changeClass();"></div>

I wrote the JavaScript as:

<script language="javascript"> 
  function change_autorefreshdiv(){
    var NAME = document.getElementById("first_name")
    NAME.className="second_name"
  } 
</script>

It's working for the first instance only. That is on page load, if I click on it, the first_name gets changed into second_name. But clicking on it again, it won't revert the second_name to first_name.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to define the second class name. Currently, you have got a function which changes the class name to a hard-coded value, independent on the current class name. See also: MDN: if...else

function change_autorefreshdiv(){
    var NAME = document.getElementById("first_name");
    var currentClass = NAME.className;
    if (currentClass == "second_name") { // Check the current class name
        NAME.className = "first_name";   // Set other class name
    } else {
        NAME.className = "second_name";  // Otherwise, use `second_name`
    }
}   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...