简体   繁体   English

将属性传递给 thymeleaf 中的外部 javascript 文件-作为空字符串传递

[英]Pass an attribute to an external javascript file in thymeleaf- passed as empty string

From my controller I add an Object to my model, which I can access within the Html.从我的控制器中,我将一个对象添加到我的模型中,我可以在 Html 中访问它。 example例子

 redir.addFlashAttribute("userId",userId);
 return modelAndView;

Within the HTML if I access the userId在 HTML 中,如果我访问 userId

 <input type="hidden" id="userId" th:value="${userId}" /> - 

I can see the result.我可以看到结果。 I have an external JS file, that has a function that takes as an input parameter userId.我有一个外部 JS 文件,它有一个将 userId 作为输入参数的函数。 How do I read the userId directly to the JS file ?如何将 userId 直接读取到 JS 文件中? Cuz if I do it like this :因为如果我这样做:

var userId=$("userId").val(); 

the userId doesn't take the value. userId 不接受该值。 It shows an empty string.它显示一个空字符串。 How do I fix this ?我该如何解决 ?

您必须在 html #userId为 id 使用选择器

var userId=$("#userId").val();

jQuery's val method looks at the value attribute, so it ignores th:value . jQuery 的val方法查看value属性,因此它忽略th:value You need to use the .attr method, eg $('#userId).attr('th-value') .您需要使用.attr方法,例如$('#userId).attr('th-value')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM