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

点击meat-butn-on按钮报错:Cannot set properties of undefined (setting 'display')

问题原因及解决方案

错误核心原因

你通过document.getElementsByClassName("testing")获取到的是HTMLCollection类数组对象,而非单个DOM元素。直接调用btn.style相当于给整个集合设置样式,但集合本身并没有style属性,这就是控制台抛出"Cannot set properties of undefined (setting 'display')"错误的根本原因。

同时还有两个潜在问题需要注意:

  • 循环生成的按钮和内容都使用了重复的id="click"和id="try",DOM中ID必须唯一,重复ID会导致选择器逻辑混乱。
  • 当前代码用全局变量b控制显示状态,点击任意按钮都会同步切换所有内容的显示/隐藏,大概率不符合你“单个按钮对应单个内容”的预期。

修复步骤

1. 修正EJS模板,建立元素关联并移除重复ID

修改icook.ejs,给按钮和对应内容添加索引关联属性,同时默认隐藏内容:

<div class="meat-table" >
  <% for(let i=0; i<foodName.length; i++) { %>
     <button class="meat-butn-on" data-index="<%= i %>">
       <%- foodName[i].emoji %> <%= foodName[i].foodName %>  
     </button>
  <% } %>
</div>
<div class="result">
 Let's see what's delicacy for today!
   <% for(let i=0; i<foodName.length; i++) { %>
     <p class="testing" data-index="<%= i %>" style="display: none;">
       <a href="<%= foodName[i].Link %>" role="button"><%= foodName[i].foodName %></a>
     </p>
   <% } %>
</div>

2. 修正JS逻辑,操作对应DOM元素

如果需求是单个按钮控制对应内容的显示/隐藏,修改display.js如下:

const buttons = document.getElementsByClassName("meat-butn-on");
const contents = document.getElementsByClassName("testing");

for (let i = 0; i < buttons.length; i++) {
  buttons[i].onclick = function () {
    const index = this.getAttribute('data-index');
    const targetContent = contents[index];
    // 切换显示状态
    targetContent.style.display = targetContent.style.display === 'block' ? 'none' : 'block';
  };
}

如果需求是点击任意按钮切换所有内容的显示/隐藏,则修改为:

let isAllVisible = false;
const buttons = document.getElementsByClassName("meat-butn-on");
const contents = document.getElementsByClassName("testing");

for (let i = 0; i < buttons.length; i++) {
  buttons[i].onclick = function () {
    isAllVisible = !isAllVisible;
    const displayStyle = isAllVisible ? 'block' : 'none';
    // 遍历所有内容元素统一设置样式
    for (let j = 0; j < contents.length; j++) {
      contents[j].style.display = displayStyle;
    }
  };
}

额外提示

  • getElementsByClassName返回动态集合,现代浏览器也可使用document.querySelectorAll(".meat-butn-on")获取NodeList,用法基本一致。
  • 永远不要在DOM中使用重复ID,这会导致后续JS选择器、CSS样式出现不可预期的问题。

内容的提问来源于stack exchange,提问作者HHck C.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:56:13