【问题标题】:How to use a select element to insert a Thymleaf fragment?如何使用选择元素插入 Thymeleaf 片段?
【发布时间】:2021-08-08 15:04:47
【问题描述】:

我想使用 HTML 选择元素来更改显示的百里香片段。

html代码:

<label for="algorithm">Algorithm</label>
<select id="algorithm" onchange="getAlgorithmParams(this.value, '#algParams')">
    <option value="">Select Algorithm</option>
    <option value="ZeroR">ZeroR</option>
    <option value="OneR">OneR</option>
    <option value="NaiveBayes">Naive Bayes</option>
    <option value="IBK">IBK</option>
    <option value="J48">J48</option>
</select>

<div id="algParams"></div>

javascript代码:

getAlgorithmParams = function (algorithmName, elementID){
    console.log(algorithmName);
    console.log(elementID);
    document.querySelector(elementID).innerHTML = "<div th:insert='~{/fragments/parameter-fragments :: " + algorithmName + "}'></div>";
}

when the selection is changed i want the div element with the id "algParams" to display a different thymeleaf fragment.当我运行它时,它会在我检查页面时显示在页面元素中。

<div th:insert="~{/fragments/parameter-fragments :: OneR}"></div>

这是正确的表示法,应该可以工作。

【问题讨论】:

    标签: javascript html spring-boot thymeleaf


    【解决方案1】:

    Thymeleaf 在服务器端呈现 HTML。一旦 HTML 在浏览器中,Thymeleaf 就不再“活跃”了。

    您可以为页面上隐藏的每个选项插入&lt;div&gt;,然后使用 JavaScript 使选中的选项可见。

    所以你的 Thymeleaf 模板有:

    <div class="hidden">
      <div id="ZeroR" th:insert="~{/fragments/parameter-fragments :: ZeroR}"></div>
      <div id="OneR" th:insert="~{/fragments/parameter-fragments :: OneR}"></div>
      <div id="NaiveBayes" th:insert="~{/fragments/parameter-fragments :: NaiveBayes}"></div>
      <div id="IBK" th:insert="~{/fragments/parameter-fragments :: IBK}"></div>
      <div id="J48" th:insert="~{/fragments/parameter-fragments :: J48}"></div>
    </div>
    

    这将呈现发送到浏览器的 HTML 中的所有这些片段。

    然后在您的 JavaScript 函数中,通过 id 选择您需要的 div 并将其设置为 innerHTML

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多