首页 > 解决方案 > Thymeleaf - 如何交互和重新加载 Javascript?

问题描述

在没有页面刷新的情况下,我正在调用一个 ajax 请求,该请求会发送到控制器并带来一个 Thymeleaf 片段,

单击按钮时,我请求使用 ajax 的控制器获取片段。每次我单击按钮时,都会调用相同的片段,但使用不同的<p>标签innerHTML

<div id="express" th:fragment="Display">
<p id="app">Include details about your goals</p>
</div>

第一次,js 效果很好,拆分成数组并添加 span 标签,但是动态替换的新内容的问题。问题出在 javascript 方面,当标签innerHTML内部不同的新片段<p>来时,Javascript 不起作用。我需要刷新页面以重新运行我不想刷新的 js。

这是js

let comp = document.getElementById("app").innerHTML; 
let struct = comp.split(" "); 

document.getElementById("app").innerHTML = struct.reduce((acc, word, index) => {
  return `${acc} <span class="word">${word}</span>`;
}, "");

const handleClick = () => {
axios.post(url)
   .then(response => {
       console.log(response.data);
           $("#express").replaceWith($recievedHTML);
   })
   .catch(error => {
       console.log(error);
   });
}

标签: javascriptspring-bootthymeleaf

解决方案


假设你有你的 HTML 页面,里面有你的 JS 文件,或者你<script>直接在标签中添加了 JS。就像是 ...

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <script src="/path/lib/jquery/3.5.1/jquery.min-dc5e7f18c8d36ac1d3d4753a87c98d0a.js" type="text/javascript"></script>
    <script src="/path/js/your_file.min-cf4fcae72d4468307341eac1012bb6d8.js" type="text/javascript"></script>
</head>
<body>

    <div id="express" th:fragment="Display">
        <p id="app">Include details about your goals</p>
    </div>

</body>
</html>

此页面的 Javascript 可能看起来像...

$(function() {

    function my_load_function() {
        // do your loading procedures here
        // for example I just copied your inline code...
        let comp = document.getElementById("app").innerHTML; 
        let struct = comp.split(" "); 
    
        document.getElementById("app").innerHTML = struct.reduce((acc, word, index) => {
        return `${acc} <span class="word">${word}</span>`;
        }, "");
    
    }
    
    function my_do_something_else_function() {
        // dosomething else over here
    }
    
    const handleClick = () => {
    axios.post(url)
       .then(response => {
           console.log(response.data);
           // what is '$recievedHTML'? should it be response.data?; 
           // ayway, you said replacement works;
           $("#express").replaceWith($recievedHTML);
           // after this call any function again
           my_load_function();
           my_do_something_else_function();
       })
       .catch(error => {
           console.log(error);
       });
    };
    
    // call your loading function first time
    my_load_function();

});

我已经在 J​​S 代码的注释中添加了我的补充说明。请注意,我只是直接用SO写的,甚至没有尝试运行,所以可能有一些错别字。


推荐阅读