我不断收到此错误:未捕获的类型错误:无法设置 null 的属性(设置 'innerHTML')
或:未捕获的类型错误:无法设置 null 的属性(设置“textContent”)
在模式打开后尝试更改锚标记的文本时。
这里是模态:
<!-- Success Modal -->
<div class="modal-container" id="modal">
<div class="modal-main">
<img
src="./assets/images/icon-success.svg"
alt="success image"
/>
<h1 class="modal-header">Thanks for subscribing!</h1>
<p>
A confirmation email has been sent to
<a href="#" id="modal-email">test</a>. Please open it and
click the button inside to confirm your subscription.
</p>
</div>
<button id="dismiss-btn">Dismiss message</button>
</div>
表格:
<form id="form">
<label for="email">Email address</label>
<input
type="email"
name="email"
id="email"
placeholder="[email protected]"
/>
<button id="button">Subscribe to monthly newsletter</button>
</form>
和Javascript:
const form = document.getElementById("form");
const btn = document.getElementById("button");
const dismissBtn = document.getElementById("dismiss-btn");
const modal = document.getElementById("modal");
const modelEmail = document.getElementById("model-email");
form.addEventListener("submit", function (e) {
e.preventDefault();
modal.style.display = "block";
let formData = new FormData(this);
let inputValue = formData.get("email");
console.log(inputValue);
modelEmail.textContent = "example";
});
dismissBtn.onclick = function () {
modal.style.display = "none";
};
当控制台记录 inputValue 时,正确的值出现在控制台中,但是当尝试更改模式中锚标记的 textContent 时,我不断收到错误。无论我使用 inputValue 还是[在本例中]“example”字符串,我都会不断收到 null 错误。
似乎
modelEmail
没有引用该元素。所以属性textContent
不存在。据我所知有两种情况:
您用以下方式查询您的
modelEmail
:document.getElementById("model-email")
,这似乎是您犯了一个拼写错误,因为在您的html中,与此最接近的ID是“modal-email”。
如果拼写错误只是在帖子中而不是在您的代码中,那么您很可能会在渲染之前尝试访问模式。例如,如果您最初尝试使用 js 访问模式,但在提交之前不渲染模式,就会发生这种情况。在这种情况下,您必须将 dom 查询移动到事件内部,以保证查询将在模态渲染后运行。