javascript Uncaught TypeError: elem is null (function parameter) [重复]

问题描述 投票:0回答:0

目前我正在一个 wordpress 网站上工作,该网站为用户提供可以淡入或淡出的元素。特别是它是一个显示或隐藏的声音按钮。

对于点击功能,我写了一个可以应用于多个元素的基本功能。

const soundButtonMobile = document.querySelector('.mobile-sound');
const soundButtonDs = document.querySelector('.desktop-sound');

function playSound(elem){
  let isPlaying = false;
  elem.addEventListener('click', () => {

    if(!isPlaying){
      elem.classList.add('sound-on');
      isPlaying = true;
    }
    else{
      elem.classList.remove('sound-on');
      isPlaying = false;
    }
    console.log('clicked');
  });
}

if( typeof soundButtonDs !== undefined || typeof soundButtonDs !== null ) playSound(soundButtonDs);
if( typeof soundButtonMobile !== undefined || typeof soundButtonMobile !== null ) playSound(soundButtonMobile);

如果页面上不存在该按钮,则函数参数 (elem) 会导致错误: 未捕获的类型错误:elem 为 null

处理此类错误的更好方法是什么,因为它也是一个基本的 vanila js - 没有 onload 函数等,.js 文件看起来像你在上面看到的那样。

处理良好发展的任何帮助或进一步了解都有助于... 感谢你 米

我试图封装 js 函数 - 不确定它是否是正确的术语

$(function() { /* here i added the code from above */ }
window.onload=function() {  /* here i added the code from above */ }
$(document).ready(function() {  /* here i added the code from above */ });
javascript function variables scope
© www.soinside.com 2019 - 2024. All rights reserved.