我想要两个基本上是类别的按钮。我们将它们命名为类别 A 和类别 B。它们分别显示在左侧和右侧。下面我想显示一些取决于所选类别(即单击的按钮)的文本,以便类别 A 显示文本 A,类别 B 显示文本 B。
如果是 html 的话。我正在制作一个 WordPress 主页。
我能够安装一个切换文本的按钮(基本上按钮 1 = A 类)。但我无法插入第二个按钮(基本上按钮 2 = B 类)。有任何想法吗?高度赞赏!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Click the button to swap the text of the DIV element:</p>
<p><button onclick="myFunction()">Click Me</button></p>
<div id="myDIV">Hello</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.innerHTML === "Hello") {
x.innerHTML = "Swapped text!";
} else {
x.innerHTML = "Hello";
}
}
</script>
</body>
</html>
我希望有 2 个按钮显示 2 个类别,文本应根据单击的按钮进行切换。
最佳答案
可以将描述放入属性中,然后在单击时获取属性值并更改描述的 html。这是jsFiddle
<div>
<button class="js-button default-button" data-description="Category A's Description" onclick="myFunction(this)">
Category A
</button>
<button class="js-button default-button" data-description="Category B's Description" onclick="myFunction(this)">
Category B
</button>
</div>
<div id="js-description" class="description">
</div>
<script>
function myFunction(elem) {
var x = document.getElementById("js-description");
var description = elem.getAttribute('data-description');
x.innerHTML = description;
var button = document.getElementsByClassName('js-button');
for (var i = 0; i < button.length; i++) {
button[i].classList.remove('active-button');
}
elem.classList.add('active-button');
}
</script>
<style>
.default-button{
font-size:16px;
border-radius: 4px;
padding:7px 12px;
}
.active-button{
background:blue;
color:#fff;
}
.description{
margin-top:20px;
}
</style>
关于html - 在多个按钮之间切换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55710416/