TypeError:无法读取Null的属性(读取' addeventListener')JavaScript
我正在尝试添加一个按钮,但它向我显示了这个错误。 这是我的HTML代码
<div card-container>
<template class="mainTemplate">
<div class="cards">
<div class="card">
<img data-image src="" alt="">
<div data-title class="header"></div>
<div data-body class="body"></div>
<button data-button class="btn">read more</button>
<p data-paragraph class="fullText"></p>
</div>
</div>
</template>
</div>
,这是JavaScript代码
let showDitail = document.querySelector(".btn");
showDitail.addEventListener("click", showMore);
function showMore(){
alert("e")
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用的是
&lt; template&gt;
标签,该标签是保存HTML标记的元素,但未在页面加载上渲染。为了渲染其内容,必须使用javaScript来处理
&gt;
元素,使用HTML结构作为 - 实际上 - 用于填充另一个结构的模板(表格,divs divs grid,a divs grid,a divs grid,a ETC。)。由于
&lt; template&gt;
的子元素尚未属于DOM的一部分,let showditail = document.queryselector(“。btn”);
将导致> null
。这就是为什么您无法将事件绑定到它的原因。将标签更改为其他东西(也许是
div
),或者通过JavaScript正确处理模板。You're using the
<template>
tag, which is an element that holds html markup but it's not rendered on page load.In order to render its contents, one has to handle the
<template>
element via javascript, using the html structure as - in fact - a template for filling another structure (a table, a divs grid, etc.).Since the sub-elements of
<template>
are not part of the DOM yet,let showDitail = document.querySelector(".btn");
will result innull
. That's why you cannot bind events to it.Either change the tag to something else (a
div
maybe), or handle the template properly via javascript.https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template