简体   繁体   English

用于多个页面和按钮的addEventListener

[英]addEventListener for multiple pages and buttons

I'm way too used to working in react and components so doing this all in vanilla JS makes my brain go blank some times. 我也很习惯于在React和Components中工作,因此在Vanilla JS中完成所有这些工作会使我的大脑有些空白。

I have a website with multiple pages/URLs. 我有一个包含多个页面/ URL的网站。 Certain pages have unique styles that users interact with. 某些页面具有与用户交互的独特样式。

I have a single file script.js . 我只有一个文件script.js I get elements with document.getElementsByClassName , I then use an addEventListener for 'clicks' and what not. 我得到带有document.getElementsByClassName元素,然后将addEventListener用作“单击”,而不是。 When I only worked on one page I never noticed that when I started building out the second page the script breaks because it can't find the element (which was on the previous page). 当我只在一页上工作时,我从没注意到当我开始构建第二页时脚本会中断,因为它找不到元素(在上一页中)。

This does make sense but how do you work around this? 这确实有意义,但是您如何解决呢? My entire script is encapulslated with window.onload . 我的整个脚本都被window.onload迷住了。

For example, 例如,

Page1.html Page1.html

<button class="first"> Click me </button>

Page2.html Page2.html

<button class="second"> Click me </div>

Scrip.js Scrip.js

var buttonOne = document.getElementsByClassName("first")[0];
var buttonTwo = document.getElementsByClassName("second")[0];

buttonOne.addEventListener('click',function(){
        firstFun(); 
})

buttonTwo.addEventListener('click',function(){
        secondFun(); 
})

function firstFun () { .. }
function secondFun () { .. }

In which this script wouldn't work because it would break trying to find the element and adding the event listener. 在这种情况下,此脚本将不起作用,因为它会尝试查找元素并添加事件侦听器而中断。

Another solution can be to add onclick event to the buttons, like below 另一个解决方案是将onclick事件添加到按钮,如下所示

<button onclick="myFunction()">Click me</button>.

And define the function in js fie. 并在js fie中定义函数。

As @epascarello mentioned the solution is simple. 正如@epascarello提到的那样,解决方案很简单。

Wrap the event listeners in an if (element) statement. 将事件侦听器包装在if (element)语句中。

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

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