单击时更改div的类? [英] Changing the class of a div when clicking on it?
问题描述
如何点击它来更改div类名?例如:
How can I change a div class name when clicking on it? Eg:
<div class="first_name" onclick="changeClass();" id="first_name"></div>
当用户点击div时,我想按如下方式更改
I want to change it as follows, when a user clicks on the div
<div class="second_name" onclick="changeClass();"></div>
我把JavaScript写成:
I wrote the JavaScript as:
<script language="javascript">
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name")
NAME.className="second_name"
}
</script>
它仅适用于第一个实例。这是在页面加载时,如果我点击它, first_name
会变为 second_name
。但是再次单击它,它不会将 second_name
还原为 first_name
。
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
.
推荐答案
您必须定义第二个类名。目前,您有一个函数可以将类名更改为硬编码值,与当前类名无关。另请参阅: MDN:if ... else
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`
}
}
这篇关于单击时更改div的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!