我想实现在杰基尔帖子页的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 null
error控制台。 https://govtexam.jus.in/maharashtra/2018/12/29/11.html
好像你是在加载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
你没有带班“共享BTN2”元素。所以`document.querySelector(”共享BTN2' )返回null。
请类share-btn2
添加到您希望将点击事件监听器绑定按钮。