【问题标题】:Inline javascript with Spring Boot, Thymeleaf, Dandelion使用 Spring Boot、Thymeleaf、Dandelion 的内联 JavaScript
【发布时间】:2016-07-26 09:21:21
【问题描述】:

我想替换这个:

<body onload="
      $('input[name=startDate]').focus();
      $(function () { 
        $('#startDate').datepicker({ dateFormat: 'mm/dd/yy'});
      });
 ">

使用内联 javascript - 类似于:

<script th:inline="javascript">
/*<![CDATA[*/
    $( document ).ready(function() {
        $('input[name=startDate]').focus();
        $('#startDate').datepicker({ dateFormat: 'mm/dd/yy' });
    });
/*]]>*/
</script>

但是,这不起作用。错误是:ReferenceError: $ is not defined

有人知道如何让它工作吗?

【问题讨论】:

  • 在这段代码执行之前你有没有调用jquery lib文件?

标签: jquery spring spring-boot thymeleaf dandelion


【解决方案1】:

你这样做了吗:

你的控制器类:

@Grab("org.webjars:jquery:2.1.1")
@Grab("thymeleaf-spring4")
@Controller
class MyApp{...}

你的 html (tymeleaf)

    <head>
          <title>blablabla</title>
          <script src="webjars/jquery/2.1.1/jquery.min.js"></script>

 <script th:inline="javascript">
/*<![CDATA[*/
    $( document ).ready(function() {
        $('input[name=startDate]').focus();
        $('#startDate').datepicker({ dateFormat: 'mm/dd/yy' });
    });
/*]]>*/
</script>
            </head>

【讨论】:

  • 这几乎是正确的答案,我在自己的响应中对其进行了增强,以包括 spring 配置类。谢谢。
【解决方案2】:

感谢上面的提示,我能够解决这个问题:

添加适当的依赖:

<dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>2.2.4</version>
        <scope>compile</scope>
</dependency>

添加配置钩子:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }
}

最后,正确导入脚本:

<script th:src="@{/webjars/jquery/2.2.4/jquery.min.js}"></script>

然后在内联 javascript 中正确调用 jQuery 就绪函数。

【讨论】:

    【解决方案3】:

    请补充:

    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    

    在你的脚本块之前。

    $ 是 jQuery 的一部分。您需要添加它的库/实现文件才能使用它。

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2017-06-28
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多