脚本不起作用。我想制作" tiposDeFrutas"当我点击" nombreDeLista"时显示属性可见。我还添加了CSS文档。
.tiposDeFrutas {
display: none;
}

<!DOCTYPE html>
<html>
<head>
<title>Pruebas HTML</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel=StyleSheet href="newcss.css" type="text/css" media=screen>
<script>
document.onload = function() {
document.getElementById("nombreDeLista").onclick = function() {
document.getElementsByClassName("tiposDeFrutas").style.display = "block";
};
};
</script>
</head>
<body>
<div id="nombreDeLista">Frutas</div>
<div class="tiposDeFrutas">Pera</div>
<div class="tiposDeFrutas">Limón</div>
</body>
</html>
&#13;
答案 0 :(得分:6)
document.getElementsByClassName("tiposDeFrutas")
将返回一个对象数组,您可以使用[0]
定位第一个对象:
document.getElementsByClassName("tiposDeFrutas")[0].style.display = "block";
如果要显示所有元素,可以使用for循环遍历它们。
document.getElementById("nombreDeLista").addEventListener('click', showAll, false);
function showAll() {
var tiposDeFrutas = document.getElementsByClassName("tiposDeFrutas");
for (var i = 0; i < tiposDeFrutas.length; i++) {
tiposDeFrutas[i].style.display = "block";
}
}
.tiposDeFrutas {
display: none;
}
<div id="nombreDeLista">Frutas</div>
<div class="tiposDeFrutas">Pera</div>
<div class="tiposDeFrutas">Limón</div>
答案 1 :(得分:0)
最终代码
<!DOCTYPE html>
<html>
<head>
<title>Pruebas HTML</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel=StyleSheet href="newcss.css" type="text/css" media=screen>
<script>
window.onload = function () {
document.getElementById("nombreDeLista").onclick = function () {
elementos = document.getElementsByClassName("tiposDeFrutas");
for (var i = 0; i < elementos.length; i++) {
elementos[i].style.display = "block";
}
};
};
</script>
</head>
<body>
<div id="nombreDeLista">Frutas</div>
<div class="tiposDeFrutas">Pera</div>
<div class="tiposDeFrutas">Limón</div>
</body>
</html>