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

如何将EJS中的articles集合传递给JavaScript函数?

问题

问题背景

当前逻辑:

  • 从数据库获取articles集合并传入index.ejs视图;
  • 在index.ejs中通过<% articles.forEach((article, index) => { %>生成文章列表。

预期逻辑:

  • articles集合传入index.ejs视图;
  • 生成列表后,用户点击文章标题;
  • JavaScript函数接收articles集合与文章id参数;
  • 函数根据id找到对应文章,获取其content属性并展示在页面元素中。

目前尝试实现但未成功,有两个疑问:

  1. 我的代码写法是否正确?
  2. 该如何正确实现此功能?

当前代码片段(index.ejs)

标签代码:

<a style="font-weight: bold;" href="#"><%=article.title%></a>

左侧菜单片段:

<!-- 其他代码省略 -->
 <!-- LEFT MENU -->
<div class="col-3 d-flex">
    <aside class="bg-danger bg-gradient w-100 d-flex justify-content-left align-items-center text-dark fs-5">                                
        <% if (articles.length > 0) { %>
            <ul>
                <% articles.forEach((article, index) => { %>
                <li>
                    <input type="hidden" class="articles" name="articles[]" value="<%= article.id %>">     
                    <span>
                        <a style="font-weight: bold;" href="#"><%=article.title%></a>
                    </span>    
<!-- 其他代码省略 -->

尝试的代码方案

方案1:点击时传递参数

标签代码:

<a style="font-weight: bold;" href="#" onclick="setMessage3('<%=articles%>', '<%=article.id%>')"><%=article.title%></a>

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:18:43