Включить скрипт из внешнего файла в html - PullRequest
0 голосов
/ 06 марта 2020

У меня есть шаблон с чабрецом для ввода формы, где я использую скрипт js. Когда в шаблоне он работает нормально, но когда я пытаюсь исключить его из внешнего файла, он перестает работать. Возможно, я неправильно импортирую, но не знаю, что здесь изменить, потому что все кажется нормальным. Вот файлы шаблонов и скриптов (langSelect. js)

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<header>
    <title th:text="#{input.form.title}"></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</header>
<body>
<h1 th:text="#{input.form}"></h1>
<div class="col-md-6">
    <form action="#" th:action="@{/register}" th:object="${userForm}" method="post">
        <div class="form-row">
            <div class="form-group col">
                <label th:text="#{first.name}"></label>
                <input type="text" th:unless="${#fields.hasErrors('firstName')}" class="form-control"
                       th:placeholder="#{first.name}" th:field="*{firstName}">
                <input type="text" th:if="${#fields.hasErrors('firstName')}" class="form-control alert-danger"
                       th:placeholder="#{first.name}" th:field="*{firstName}">
                <span th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"></span>
            </div>
            <div class="form-group col">
                <label th:text="#{last.name}"></label>
                <input type="text" th:unless="${#fields.hasErrors('lastName')}" class="form-control"
                       th:placeholder="#{last.name}" th:field="*{lastName}">
                <input type="text" th:if="${#fields.hasErrors('lastName')}" class="form-control alert-danger"
                       th:placeholder="#{last.name}" th:field="*{lastName}">
                <span th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}"></span>
            </div>
        </div>
        <div class="form-group">
            <label th:text="#{email}"></label>
            <input type="text" th:unless="${#fields.hasErrors('email')}" class="form-control"
                   th:placeholder="#{email}" th:field="*{email}">
            <input type="text" th:if="${#fields.hasErrors('email')}" class="form-control alert-danger"
                   th:placeholder="#{email}" th:field="*{email}">
            <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
        </div>
        <div class="form-group">
            <label th:text="#{password}"></label>
            <input type="text" th:unless="${#fields.hasErrors('passwordsEqual')}" class="form-control"
                   th:placeholder="#{password}" th:field="*{password}">
            <input type="text" th:if="${#fields.hasErrors('passwordsEqual')}" class="form-control alert-danger"
                   th:placeholder="#{password}" th:field="*{password}">
            <span th:if="${#fields.hasErrors('passwordsEqual')}" th:errors="*{password}"></span>
        </div>
        <div class="form-group">
            <label th:text="#{password.repeat}"></label>
            <input type="text" th:unless="${#fields.hasErrors('passwordsEqual')}" class="form-control"
                   th:placeholder="#{password.repeat}" th:field="*{passwordRepeat}">
            <input type="text" th:if="${#fields.hasErrors('passwordsEqual')}" class="form-control alert-danger"
                   th:placeholder="#{password.repeat}" th:field="*{passwordRepeat}">
            <span class="error" th:if="${#fields.hasErrors('passwordsEqual')}" th:errors="*{passwordsEqual}"></span>
        </div>
        <input class="btn-primary" type="submit" value="Submit"/> <input class="btn-primary" type="reset"
                                                                         value="Reset"/>
    </form>
    <p></p>
    <p></p>
    <p></p>
    <span th:text="#{lang.change}"></span>
    <select id="locales">
        <option value=""></option>
        <option value="en" th:text="#{lang.eng}"></option>
        <option value="ru" th:text="#{lang.ru}"></option>
        <script type="javascript" src="langSelect.js"></script>
    </select>

</div>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
        crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
        integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
        crossorigin="anonymous"></script>
</body>
</html>
$(document).ready(function () {
    $("#locales").change(function () {
        var selectedOption = $('#locales').val();
        var queryString = window.location.search;
        var urlParams = new URLSearchParams(queryString);
        if (selectedOption !== '') {
            var newUrl;
            if (urlParams.has('lang')) {
                var reExp = /lang=\w+/;
                newUrl = queryString.replace(reExp, "lang=" + selectedOption);
            } else {
                if (queryString.includes('?')) {
                    newUrl = queryString.concat("&lang=" + selectedOption);
                } else {
                    newUrl = queryString.concat("?lang=" + selectedOption);
                }
            }
            window.location.replace(newUrl);
        }
    });
});

1 Ответ

1 голос
/ 06 марта 2020

Пожалуйста, используйте th:src следующим образом:

 <script th:src="@{/js/langSelect.js}"></script>

Предполагается, что ваш файл находится в папке js, которая находится в папке static, поскольку предполагается, что папка static быть root path.

Если ваш файл находится непосредственно в папке static, попробуйте следующее:

<script th:src="@{langSelect.js}"></script>

Также обратите внимание, что вам не нужно импортировать сценарий в том месте, где он необходим.

Ваш сценарий будет запускаться автоматически, когда ваша страница завершит загрузку, поэтому в принципе не имеет значения, где вы его поместили, но обычно до того, как закрывающий тег body считается хорошим практика (так что там вместе с другими сценариями).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...