问题
I've searched but frankly, do not know enough about JS to make sense of all of the other "combine these 2 functions" posts already out there.
I am using a script to slide out a Contact Panel. I duplicated this script to then slide out the About Panel.
I want to consolidate both into one script to tidy things up. Possible?
Contact Panel:
<script type="text/javascript">
function showContactPanel() {
var elem = document.getElementById("contact-panel");
if (elem.classList) {
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
</script>
Duplicated for the About Panel:
<script type="text/javascript">
function showAboutPanel() {
var elem = document.getElementById("about-panel");
if (elem.classList) {
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
</script>
回答1:
You could pass the panel ID as a parameter:
function showPanel(id) {
var elem = document.getElementById(id);
if (elem.classList) {
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
and then call it that way:
showPanel("about-panel");
or
showPanel("contact-panel");
回答2:
So change your function signature to take a parameter for the element in question:
function showPanel(panelId) {
var elem = document.getElementById(panelId);
...
and call it:
showPanel("contact-panel");
回答3:
You could pass the id of the panel as an argument to the function:
<script type="text/javascript">
function showPanel(panelId) {
var elem = document.getElementById(panelId);
if (elem.classList) {
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
</script>
See JavaScript Function Parameters for more information on function parameters.
来源:https://stackoverflow.com/questions/25558651/combining-two-identical-javascripts-into-one