Django的js文件没有响应(DOMContentLoaded)

问题出现的原因是因为当浏览器解析到"script"标签并执行其中的JavaScript代码时,页面上的DOM元素尚未完全加载和渲染。这意味着,当尝试通过document.getElementById('create-theme-button')获取元素时,该元素还不存在,导致addEventListener无法被正确绑定到任何元素上。

为了解决这个问题,您可以将JavaScript代码放置在页面加载完成后执行。这可以通过将JavaScript代码包裹在一个监听DOMContentLoaded事件的处理函数中来实现,如下所示:

原始代码:

html 复制代码
    <script>
        document.getElementById('create-theme-button').addEventListener('click', function() {
        // 创建输入框
        var input = document.createElement('input');
        input.type = 'text';
        input.placeholder = '请输入主题名称...';
        
        // 创建添加按钮
        var addButton = document.createElement('button');
        addButton.textContent = '添加';
        addButton.onclick = function() {
            // 这里可以添加点击"添加"按钮之后的逻辑
            // 例如,发送数据到服务器或在页面上显示新的主题
            alert('主题:' + input.value + ' 已添加(这里应该替换为真实的添加逻辑)');
        };
        
        // 获取容器并将输入框和按钮添加到页面上
        var container = document.getElementById('theme-input-container');
        container.appendChild(input);
        container.appendChild(addButton);
    });

    </script>

修改后

html 复制代码
<script>
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('create-theme-button').addEventListener('click', function() {
            // 创建输入框
            var input = document.createElement('input');
            input.type = 'text';
            input.placeholder = '请输入主题名称...';

            // 创建添加按钮
            var addButton = document.createElement('button');
            addButton.textContent = '添加';
            addButton.onclick = function() {
                // 这里可以添加点击"添加"按钮之后的逻辑
                alert('主题:' + input.value + ' 已添加(这里应该替换为真实的添加逻辑)');
            };

            // 获取容器并将输入框和按钮添加到页面上
            var container = document.getElementById('theme-input-container');
            container.appendChild(input);
            container.appendChild(addButton);
        });
    });
</script>

这样,Django就能正常响应js代码或者js文件的功能了

相关推荐
Java后端的Ai之路1 天前
【Python 教程15】-Python和Web
python
冬奇Lab1 天前
一天一个开源项目(第15篇):MapToPoster - 用代码将城市地图转换为精美的海报设计
python·开源
二十雨辰1 天前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码1 天前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Daniel李华1 天前
echarts使用案例
android·javascript·echarts
北原_春希1 天前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS1 天前
echarts天气折线图
javascript·vue.js·echarts
尽意啊1 天前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜1 天前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive1 天前
Vue3使用ECharts
前端·javascript·echarts