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文件的功能了

相关推荐
洛阳吕工1 分钟前
【Python 教程】无人机 MAVLink 通信完整实战:连接飞控、接收数据与发送指令
开发语言·python·无人机
广州山泉婚姻5 分钟前
Python 虚拟环境 venv 在 VSCode 中的正确用法
人工智能·python
小白学大数据7 分钟前
Python requests + BeautifulSoup 爬取豆瓣电影图片
开发语言·python·beautifulsoup
早點睡3907 分钟前
ReactNative项目OpenHarmony三方库集成实战:react-native-inappbrowser(也可以考虑WebView)
javascript·react native·react.js
北风toto9 分钟前
Vue多文件学习项目综合案例——面经基础版,黑马vue教程
javascript·vue.js·学习
浪扼飞舟1 小时前
WPF输入验证(ValidationRule)
java·javascript·wpf
花酒锄作田8 小时前
Postgres - Listen/Notify构建轻量级发布订阅系统
python·postgresql
Thomas.Sir9 小时前
第二章:LlamaIndex 的基本概念
人工智能·python·ai·llama·llamaindex
m0_694845579 小时前
Dify部署教程:从AI原型到生产系统的一站式方案
服务器·人工智能·python·数据分析·开源
这是个栗子9 小时前
TypeScript(三)
前端·javascript·typescript·react