我正在寻找一种更改所选id的类的方法。我的目标是用java做这个,但我似乎无法弄清楚如何。所以在我的例子中,我有4个“p”标签,每个标签都有不同的id,并且所有类都是“na”,现在我要做的是当其中一个“p”标签点击它时将类交换到“under”并且导致标签加下划线。任何人都可以在这里指出我正确的方向来简化它吗?
修改
很抱歉,我忘了添加JavaScript。
function class1() {
document.getElementById("p1").className = "under";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "na";
}
function class2() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "under";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "na";
}
function class3() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "under";
document.getElementById("p4").className = "na";
}
function class4() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "under";
}
.under {
font-size: 16px;
font-weight: bold;
text-decoration: underline;
}
.na {
font-size: 16px;
font-weight: bold;
}
<p id="p1" class="na" onclick="class1()">Para1</p>
<p id="p2" class="na" onclick="class2()">Para2</p>
<p id="p3" class="na" onclick="class3()">Para3</p>
<p id="p4" class="na" onclick="class4()">Para4</p>
答案 0 :(得分:0)
看起来你的任务过于复杂。
使用jQuery,只需一个“两行”功能即可实现这一过程。
$(".na").on("click", function(){
// Remove the class under from all p element.
$(".na").removeClass("under");
// Add the class under to the one clicked.
$(this).addClass("under");
});
.under {
text-decoration: underline;
}
.na {
font-size: 16px;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1" class="na">Para1</p>
<p id="p2" class="na">Para2</p>
<p id="p3" class="na">Para3</p>
<p id="p4" class="na">Para4</p>