简体   繁体   English

JavaScript无法运行,表示element为null,但是代码运行得很混乱

[英]JavaScript won't run, says element is null, but code runs in fiddle

I'm building a thymeleaf and spring project with the java configuration. 我正在使用Java配置构建一个百里香和Spring项目。 When I try out this code in a jsfiiddle it works fine, but when I try to run it in my application I get this: TypeError: document.getElementById(...) is null . 当我在jsfiiddle中尝试此代码时,它工作正常,但是当我尝试在应用程序中运行它时,我得到了: TypeError: document.getElementById(...) is null

There is nothing wrong in the imports of the javascrips and the source renders them and the html just fine. 导入javascrips并没有错,源代码可以渲染它们,而html也可以。

The code: 编码:

HTML: HTML:

<a href="#" id="buybutton" th:id="buybutton" th:text="#{cart.buy}">Buy</a>

JavaScript: JavaScript:

document.getElementById('buybutton').addEventListener("click", function(e){
   console.log("bought"); 
});

Thymeleaf configuration (if it is of any importance): Thymeleaf配置(如果有任何重要性):

@Configuration
public class ThymeleafConfig {

@Bean
public ServletContextTemplateResolver templateResolver() {
    ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
    resolver.setPrefix("/WEB-INF/pages/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    resolver.setOrder(1);
            resolver.setCacheable(false);
            resolver.setCharacterEncoding("UTF-8");

    return resolver;
}

}

You should add click event only when the DOM is ready. 仅当DOM准备就绪时,才应添加click事件。

NOTE: In the case of jsfiddle this is default behaviour . 注意:对于jsfiddle,这是默认行为

document.addEventListener("DOMContentLoaded", function(event) { 
  document.getElementById('buybutton').addEventListener("click", function(e){
   console.log("bought"); 
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM