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

未点击按钮时onclick事件自动触发问题排查

错误原因

你在模板字符串中使用${}包裹了console.log('at least it works until here'),模板字符串的插值表达式会在字符串生成阶段立即执行,不会等到按钮点击时才触发。
每次循环匹配到符合条件的条目时,拼接HTML的过程就会主动执行一次插值里的console.log,因此会按匹配条数打印日志。此时插值会把console.log的返回值undefined插入到onclick属性中,最终生成的按钮实际为<button onclick="undefined">დაჯავშნე ახლა</button>,真正点击按钮时反而不会有任何反应。
另外你代码里写的&lt;、&quot;属于HTML转义实体,在JS中拼接innerHTML的DOM字符串时不需要写这类转义字符,否则页面会直接把这些字符渲染成普通文本,无法生成预期的div、h1、button标签。

修正后代码
for(let each in infoForThatDay) {
    if(infoForThatDay[each]['start'] == hour.substring(0, 2)) {
        let htmlRender = `
            <div class='flex-boxes'>
                <h1>${infoForThatDay[each]['title']}</h1>
                <button onclick="console.log('at least it works until here')">დაჯავშნე ახლა</button>
            </div>
        `;
        html += htmlRender;
    }
}
const wrapper = document.querySelector('.users');
wrapper.innerHTML = html;

修正后onclick绑定的是字符串形式的执行逻辑,只有点击按钮时才会触发console.log,标签也能正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 12:31:08