[英]Unable to execute scripts depending on Thymeleaf variables <script th:inline=“javascript”>
I have 2 simple scripts and 2 Thymeleaf variables, I want one script to be executed if thymeleaf variable is true, then again if other variable is true - related script to be executed and so on.我有 2 个简单的脚本和 2 个 Thymeleaf 变量,如果 thymeleaf 变量为真,我希望执行一个脚本,如果其他变量为真,则再次执行 - 要执行的相关脚本等等。 But I get the following result - if one variable is true and script executed then second script won't be execudet even if second variable is true.
但是我得到以下结果 - 如果一个变量为真并且执行了脚本,那么即使第二个变量为真,第二个脚本也不会被执行。 So shortly, only one of scripts is executed, but need both (in sequence, not the same time).
所以很快,只执行了一个脚本,但需要两个(按顺序,不是同时)。 Here is the code:
这是代码:
<script th:inline="javascript">
var flag = [[${invalidInput}]]; //Thymleaf variable
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<script th:inline="javascript">
var flag = [[${exists}]];
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<!-- MODAL -->
<div class="form-popup" id="myForm">
<form id="registration" th:action="@{/registrate}" th:object="${newUser}" method="post" class="form-container">
<h1>Registration</h1>
<div class="alert" th:if="${exists}">
User already exists! Please try again.
</div>
<div class="invalidInput" th:if="${invalidInput}">
Username or password too short.
</div>
************************************************************
<script>
function openForm() {
document.getElementById("myForm").style.display = "block";
}
@PostMapping("/registrate")
public String login (@ModelAttribute(value = "newUser") User newUser, BindingResult bindingResult, Model model) {
userValidator.validate(newUser, bindingResult);
if(usrService.isUserPresent(newUser.getUsername())){
model.addAttribute("exists",true);
return "login";
}
else if(bindingResult.hasErrors()){
model.addAttribute("invalidInput",true);
return "login";
}
I don't think you can set the window.onload
variable twice... one will simply overwrite the other.我不认为你可以设置
window.onload
变量两次......一个只会覆盖另一个。 You can either combine your logic like this:您可以像这样组合您的逻辑:
<script th:inline="javascript">
var invalidInput = [[${invalidInput}]]; //Thymleaf variable
var exists = [[${exists}]];
window.onload = function() {
if(invalidInput) {
openForm();
} else if (exists) {
openForm();
}
};
</script>
Or alternatively you could use something like jQuery, which has this functionality built in for you.或者,您也可以使用 jQuery 之类的东西,它为您内置了此功能。
https://api.jquery.com/ready/ https://api.jquery.com/ready/
When multiple functions are added via successive calls to this method, they run when the DOM is ready in the order in which they are added.
当通过连续调用此方法添加多个函数时,它们会在 DOM 准备就绪时按添加顺序运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.