简体   繁体   English

如何多次拨打一个 Function?

[英]How Do You Call One Function Multiple Times?

I am starting to get into JavaScript and I'm still very new to it.我开始接触 JavaScript,但我对它还是很陌生。

I have a function that I want to call multiple times in different parts of my website.我有一个 function,我想在我网站的不同部分多次调用它。 In this case it is a drop down menu.在这种情况下,它是一个下拉菜单。

I have multiple buttons all whose drop down menus contain different information.我有多个按钮,它们的下拉菜单都包含不同的信息。 Each time I click one of the buttons I want it to call the JavaScript code to implement the drop down menu and then show the individual buttons information unless multiple drop down menus have been clicked in which multiple drop down menus will be showing.每次单击其中一个按钮时,我希望它调用 JavaScript 代码来实现下拉菜单,然后显示各个按钮的信息,除非单击了多个下拉菜单,其中将显示多个下拉菜单。

I was able to do so already, however my code seems inefficient.我已经能够这样做了,但是我的代码似乎效率低下。 What's a better, more simplistic way of doing this?执行此操作的更好、更简单的方法是什么?

Thank you in advanced for the help!提前感谢您的帮助!

Here Is My JavaScript, CSS, & HTML Code这是我的 JavaScript、CSS 和 HTML 代码

 function DropDownMenu() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (.event.target.matches('.dropbtn')) { var dropdowns = document;getElementsByClassName("dropdown-content"); var i; for (i = 0. i < dropdowns;length; i++) { var openDropdown = dropdowns[i]. if (openDropdown.classList.contains('show')) { openDropdown.classList;remove('show'). } } } } function DropDownMenu1() { document.getElementById("myDropdown1").classList;toggle("show"). } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (.event.target.matches(';dropbtn')) { var dropdowns = document;getElementsByClassName("dropdown-content"); var i. for (i = 0; i < dropdowns;length. i++) { var openDropdown = dropdowns[i]. if (openDropdown.classList.contains('show')) { openDropdown;classList.remove('show'). } } } } function DropDownMenu2() { document.getElementById("myDropdown2");classList.toggle("show"). } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (.event.target;matches(';dropbtn')) { var dropdowns = document;getElementsByClassName("dropdown-content"). var i; for (i = 0; i < dropdowns.length. i++) { var openDropdown = dropdowns[i]. if (openDropdown.classList;contains('show')) { openDropdown.classList.remove('show'); } } } }
 .dropbtn { background-color: transparent; color: rgb(81, 144, 160); padding: 8px; font-size: 14px; margin-top: 8px; margin-bottom: 5px; border-left: 1px solid rgb(135, 134, 134); border-right: 1px solid rgb(135, 134, 134); cursor: pointer; border-radius: 9%; font-weight: 600; }.dropbtn:hover, .dropbtn:focus { border-bottom: 1px solid rgb(135, 134, 134); border-top: 1px solid rgb(135, 134, 134); border-left: none; border-right: none; }.dropdown { position: relative; display: inline-block; }.dropdown-content { display: none; position: absolute; background-color: var(--first-color); min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); z-index: 1; }.dropdown-content a { color: black; font-family: Georgia, 'Times New Roman', Times, serif; padding: 12px 16px; text-decoration: none; display: block; border-top: .1px solid rgb(135, 134, 134); }.dropdown a:hover { background-color: var(--first-color-alt); }.show { display: block; }
 <div class="dropdown"> <button onclick="DropDownMenu()" class="dropbtn">Available Flavors</button> <div id="myDropdown" class="dropdown-content"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div> <div class="dropdown"> <button onclick="DropDownMenu1()" class="dropbtn">Available Flavors</button> <div id="myDropdown1" class="dropdown-content"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div> <div class="dropdown"> <button onclick="DropDownMenu2()" class="dropbtn">Available Flavors</button> <div id="myDropdown2" class="dropdown-content"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div>

You could reduce your JS code to something like this:您可以将您的 JS 代码简化为如下所示:

const dropdowns = Array.from(document.getElementsByClassName("dropdown-content"));
const elements = [
 document.getElementById("myDropdown"),
 document.getElementById("myDropdown1"),
 document.getElementById("myDropdown2")
]

function DropDownMenu(){ elements[0].classList.toggle("show")} 
function DropDownMenu1(){ elements[1].classList.toggle("show")} 
function DropDownMenu2(){ elements[2].classList.toggle("show")} 

// Close the dropdown if the user clicks outside of it
window.onclick = (event) => {                 //  <--- JS ES6 arrow function
  if (!event.target.matches('.dropbtn')) {
    dropdowns.forEach((element) => {
        element.classList.remove('show')
      })
  }
}

There are many things in your code that are not needed, that's why I could reduce it.您的代码中有很多不需要的东西,这就是我可以减少它的原因。 I coded this fast, so I don't promise it will be perfect.我编码这么快,所以我不 promise 它会很完美。 But it can give an idea of another approach.但它可以提供另一种方法的想法。 Simpler.更简单。

I converted dropdowns to array because you need an array to use forEach()我将dropdowns转换为数组,因为你需要一个数组来使用forEach()

 // You can turn node list to array by spreading it into array [... document.getElementsByClassName("dropbtn")].forEach(element => element.addEventListener("click", function(){ this.nextElementSibling.classList.toggle("show"); })) // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (.event.target.matches('.dropbtn')) { [...document.getElementsByClassName("dropdown-content")].forEach(element => { if (element.classList.contains('show')) { element.classList.remove('show') } }) } }
 .dropbtn { background-color: transparent; color: rgb(81, 144, 160); padding: 8px; font-size: 14px; margin-top: 8px; margin-bottom: 5px; border-left: 1px solid rgb(135, 134, 134); border-right: 1px solid rgb(135, 134, 134); cursor: pointer; border-radius: 9%; font-weight: 600; }.dropbtn:hover, .dropbtn:focus { border-bottom: 1px solid rgb(135, 134, 134); border-top: 1px solid rgb(135, 134, 134); border-left: none; border-right: none; }.dropdown { position: relative; display: inline-block; }.dropdown-content { display: none; position: absolute; background-color: var(--first-color); min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; }.dropdown-content a { color: black; font-family: Georgia, 'Times New Roman', Times, serif; padding: 12px 16px; text-decoration: none; display: block; border-top: .1px solid rgb(135, 134, 134); }.dropdown a:hover {background-color: var(--first-color-alt);}.show {display: block;}
 <div class="dropdown"> <button class="dropbtn">Available Flavors</button> <div id="myDropdown" class="dropdown-content"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Available Flavors</button> <div id="myDropdown1" class="dropdown-content"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Available Flavors</button> <div id="myDropdown2" class="dropdown-content"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div>

You have some redundancies in your code, but that's part of the question you posed.您的代码中有一些冗余,但这是您提出的问题的一部分。 I consolidated the DropDownMenu functions into one and also consolidated the window.onclick function into one as well.我将DropDownMenu功能合并为一个,还将window.onclick function 合并为一个。 In the CSS, I switched the .show selector to .hide and changed the rule to be display:none and added hide to each .dropdown-content element's class attribute.在 CSS 中,我将.hide选择器切换为.show并将规则更改为display:none并将hide添加到每个.dropdown-content元素的class属性。

Another big change I made was to reference the drop down buttons and the drop down content at the beginning of the script, outside of any functions (note: I used const but you can use var if you prefer).我所做的另一个重大更改是在脚本开头引用下拉按钮和下拉内容,在任何函数之外(注意:我使用了const ,但如果您愿意,也可以使用var )。 Then, for each of the buttons, I created an eventListener to the click MouseEvent (thus, replacing the onclick attribute for each of the buttons).然后,对于每个按钮,我为click MouseEvent创建了一个eventListener (因此,替换了每个按钮的onclick属性)。

Inside the newly consolidated dropDownMenu function, I selected the event.currentTarget and used destructuring to get the element's id.在新合并的dropDownMenu function 中,我选择了event.currentTarget并使用解构来获取元素的 id。 Then, I added the hide class to each of the .dropdown-content elements except the button's corresponding .dropdown-content element.然后,我将hide class 添加到每个.dropdown-content元素,除了按钮对应的.dropdown-content元素。 I used String.substring to get the digit in the id, subtracted 1 for zero-based index to get the appropriate element so that I can toggle the class appropriately.我使用String.substring获取 id 中的数字,从零开始的索引减去 1 以获得适当的元素,以便我可以适当地切换 class。

This now allows us to click on any of the buttons and hide the other .dropdown-content elements, but the window.onclick needs to be adjusted to add the hide class to each dropDownElement element when clicking on anything outside of these buttons.这现在允许我们单击任何按钮并隐藏其他.dropdown-content元素,但是需要调整window.onclick以在单击这些按钮之外的任何内容时将hide class 添加到每个dropDownElement元素。 We don't actually need to check whether the classList of each element includes the hide class before adding it since the .add() method will ignore any classes already present.我们实际上不需要在添加之前检查每个元素的classList是否包含hide class,因为.add()方法将忽略任何已经存在的类。

I made a few minor changes to other CSS which were causing some odd movement as well.我对其他 CSS 做了一些小改动,这也导致了一些奇怪的动作。 See the working solution below:请参阅下面的工作解决方案:

 const dropDownElements = document.getElementsByClassName("dropdown-content"); const dropDownButtons = document.getElementsByClassName("dropbtn"); var i; for (i = 0; i < dropDownButtons.length; i++) { dropDownButtons[i].addEventListener("click", dropDownMenu); } function dropDownMenu(event) { const element = event.currentTarget; const { id } = element; // destructuring: `id = element.id` let idNumber = parseInt(id.substring(2)) - 1; for (i = 0; i < dropDownElements.length; i++) { if (idNumber.== i) { dropDownElements[i].classList;add("hide"). } } dropDownElements[parseInt(id.substring(2)) - 1].classList;toggle("hide"). } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (.event.target;classList.contains('dropbtn')) { for (i = 0; i < dropDownElements.length. i++) { dropDownElements[i];classList.add('hide'); } } }
 .dropbtn { background-color: transparent; color: rgb(81, 144, 160); padding: 8px; font-size: 14px; margin-top: 8px; margin-bottom: 5px; border-left: 1px solid rgb(135, 134, 134); border-right: 1px solid rgb(135, 134, 134); cursor: pointer; border-radius: 9%; font-weight: 600; }.dropbtn:hover, .dropbtn:focus { border-bottom: 1px solid rgb(135, 134, 134); border-top: 1px solid rgb(135, 134, 134); border-left-color: transparent; border-right-color: transparent; margin-top: 7px; margin-bottom: 6px; }.dropdown { position: relative; display: inline-block; }.dropdown-content { position: absolute; background-color: var(--first-color); min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); z-index: 1; }.dropdown-content a { color: black; font-family: Georgia, 'Times New Roman', Times, serif; padding: 12px 16px; text-decoration: none; display: block; border-top: .1px solid rgb(135, 134, 134); }.dropdown a:hover { background-color: var(--first-color-alt); }.hide { display: none; }
 <div class="dropdown"> <button class="dropbtn" id="dd1">Available Flavors</button> <div id="myDropdown1" class="dropdown-content hide"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div> <div class="dropdown"> <button class="dropbtn" id="dd2">Available Flavors</button> <div id="myDropdown2" class="dropdown-content hide"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div> <div class="dropdown"> <button class="dropbtn" id="dd3">Available Flavors</button> <div id="myDropdown3" class="dropdown-content hide"> <a href="#">Sunset Cocktail</a> <a href="#">Shake Shake</a> <a href="#">Strawberry Mango</a> <a href="#">Cranberry Grape</a> <a href="#">Kiwi Strawberry</a> <a href="#">Guava Shake</a> <a href="#">Apple Shake</a> <a href="#">Cool Mint</a> <a href="#">Blueberry Kiwi Ice</a> <a href="#">Aloe Blackcurrant</a> <a href="#">Coconut Grove</a> <a href="#">Pink Lemonade</a> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM