我想在一个页面上多次应用一个相同的功能,每次都应用到具有自己ID(显示和隐藏元素)的元素上。当我应用功能而不指定ID时,整个文档中的所有元素都会更改。因此,我是否必须在Javascript文件中多次指定函数,每个函数都有其自己的ID,还是可以在运行时以某种方式获取ID?
HTML
<button onclick="switchIt_stahlherstellung">
<div id="stahlherstellung">
show/hide stuff
</div>
<button onclick="switchIt_produkte">
<div id="produkte">
show/hide stuff
</div>
and so on.
Javascript
function switchIt_stahlherstellung() {
if (document.getElementById('stahlherstellung')) {
if (document.getElementById('stahlherstellung').style.display == 'none') {
document.getElementById('stahlherstellung').style.display = 'block';
}
else {
document.getElementById('stahlherstellung').style.display = 'none';
}
}
}
function switchIt_produkte() {
if (document.getElementById('produkte')) {
if (document.getElementById('produkte').style.display == 'none') {
document.getElementById('produkte').style.display = 'block';
}
else {
document.getElementById('produkte').style.display = 'none';
}
}
}
您需要了解有关功能的更多信息,尤其是参数。
例如:
function switchIt_stahlherstellung(id) {
if (document.getElementById(id)) {
if (document.getElementById(id).style.display == 'none') {
document.getElementById(id).style.display = 'block';
}
else {
document.getElementById(id).style.display = 'none';
}
}
}
然后您可以像这样调用单个函数:
switchIt_stahlherstellung('einheiten_stahlherstellung');
了解更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions