JavaScript uncatch TypeError: 无法读取 null 的属性 'style': Button Onclick 使 html 消失



在django项目中,我设置了一个JavaScript函数来选择/阻止某些页面。对于正在加载的页面,我有另一个JavaScript函数。此函数有一个onclick事件侦听器,用于向表单字段提交文本。我遇到的问题是,当我单击一个按钮向表单字段添加文本时,整个页面都会消失。两个函数都在一个名为"的静态文件中;main.js";控制台中显示的确切错误消息是…

Uncaught TypeError: Cannot read property 'style' of null
at showPage (players:6382)
at HTMLButtonElement.button.onclick (players:6388)

以下是控制单个页面的显示/阻止的功能。

function showPage(page) {
document.querySelectorAll('tbody').forEach(tbody => {tbody.style.display = 'none';})
document.querySelector(`#${page}`).style.display = 'table-row-group'; ---(This line in error message)
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('button').forEach(button => {
button.onclick = function() {
showPage(this.dataset.page); ---(This line in error message)
}           
});
});

以下是该函数所针对的按钮的html模板示例。

<button class="posbutton" data-page="page1">QB</button>

这是一个向表单字段提交文本的函数。

function myFunction(txt) {
var myTxt = txt;


if (txt.includes('QB')) {
document.getElementById("QB_name").value = myTxt;
}
else if (txt.includes('RB')) {
document.getElementById("RB_name").value = myTxt;
}
else if (txt.includes('WR')) {
document.getElementById("WR_name").value = myTxt;
}
else if (txt.includes('TE')) {
document.getElementById("TE_name").value = myTxt;
}
else if (txt.includes('K')) {
document.getElementById("K_name").value = myTxt;
}

}

下面是showPage函数所针对的html元素的一个示例。它还包含一行按钮,链接到用于提交文本的myFunction。

<tbody id="page1">

{% for q in QBpage %}
<tr>
<th scope="row">

</th>

<td><h6>{{ q.player_name }}</h6></td>
<td><input type="button"  class="btn btn-outline-primary btn-sm m-0 waves-effect" onclick="myFunction('{{ player_data.player_name }} {{ player_data.position }}')">Add</input></td>
<td><h6> {{ q.team }} </h6></td>
<td><h6> {{ q.position }}  </h6></td>
<td><h6>{{ q.points }}</h6></td>
</tr>

{% endfor %}
</tbody>

在将这两个JavaScript函数放入静态文件之前,我尝试将脚本标记以各种组合的方式放在的开头或结尾。到目前为止,这里的建议是:为什么jQuery或getElementById等DOM方法找不到元素?对我没有帮助。我在答案中尝试了很多建议,但我仍然有同样的问题。

错误at HTMLButtonElement.button.onclick (main.js:15)仍然存在,这是showPage函数中此行的showPage(this.dataset.page);

我真的很纠结。如有任何建议,不胜感激。

document.querySelector('#'+page).style.display = 'table-row-group';

使用这个

最新更新