遗漏的类型错误:无法读取空的特性“的addEventListener”在JavaScript API Webshare的

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

我想实现在杰基尔帖子页的Android铬的Web共享API。下面是我的代码。我的代码是在_layout/post.html

<script>
  document.querySelector('.share-btn2').addEventListener('click', function() {
    console.log('clicked');
    if(navigator.share) {
      navigator.share({
        title: '{{ page.title }}',
        url: {{ site.url }}{{ page.url }}
      })
      .then(() => console.log('Success'))
      .catch((error) => console.log('Error sharing', error));
    }

  });

</script>

<button class="btn btn-danger shadow-sm my-2 my-sm-0 share-btn2" type="submit" value="submit">More</button>

现在,我得到Uncaught TypeError: Cannot read property 'addEventListener' of nullerror控制台。 https://govtexam.jus.in/maharashtra/2018/12/29/11.html

javascript jekyll
2个回答
0
投票

好像你是在加载DOM之前绑定的事件。只是DOMContentLoaded事件敷在:

document.addEventListener("DOMContentLoaded", function(event) { // <-- add this wrapper
  document.querySelector('.share-btn2').addEventListener('click', function() {
    console.log('clicked');
    if (navigator.share) {
      navigator.share({
          title: '{{ page.title }}',
          url: '{{ site.url }}{{ page.url }}'
        })
        .then(() => console.log('Success'))
        .catch((error) => console.log('Error sharing', error));
    }

  });
}); // <---DOMContentLoaded closing

0
投票

你没有带班“共享BTN2”元素。所以`document.querySelector(”共享BTN2' )返回null。

请类share-btn2添加到您希望将点击事件监听器绑定按钮。

© www.soinside.com 2019 - 2024. All rights reserved.