You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让JavaScript代码在Django模板for循环的每个项上正常执行

问题根源

HTML 规范要求页面内的 id 属性必须全局唯一,你在 Django 循环中重复生成了 id="content" 的 DOM 元素,editormd 的 markdownToHTML 方法传入 id 时只会匹配到第一个符合条件的元素,因此只有第一条内容生效。

调整步骤

1. 修改Django模板代码

给循环生成的容器添加统一的class标识,同时生成唯一id:

{% for entry in entry_list %}
<div class="markdown-content" id="content-{{ forloop.counter }}">
    <textarea>{{ entry.content|truncatechars_html:180 }}</textarea>
</div>
{% endfor %}

其中forloop.counter是Django模板内置的循环计数器,从1开始递增,可保证每个容器的id唯一。

2. 修改Javascript代码

遍历所有markdown内容容器,逐个调用转换方法:

<script>
    $(function () {
        // 遍历所有markdown内容容器
        $(".markdown-content").each(function () {
            const currentId = $(this).attr("id");
            editormd.markdownToHTML(currentId, {
                //htmlDecode      : "style,script,iframe",  // you can filter tags decode
                emoji           : true,
                taskList        : true,
                tex             : true,
                flowChart       : true,
                sequenceDiagram : true,
            });
        });
  
        $(".reference-link").each(function (i,obj) {
          console.log(obj)
        })
    })
</script>

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:24:04