如何在 Jquery 选择器中使用 JSTL var
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7121905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JSTL var in Jquery selector
提问by xyz
I am using following Jquery selector
我正在使用以下 Jquery 选择器
$("#selectedQuery td input:radio").attr('checked', true);
Where selectedQuery
is a JSTL variable declared as
selectedQuery
JSTL 变量在哪里声明为
<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />
I tested the selector with hard coded values and it's working fine but no luck when used with selectedQuery
.
How can we use JSTL <c:set>
var in Jquery ? Is there any work around ?
我用硬编码值测试了选择器,它工作正常,但与selectedQuery
.
我们如何<c:set>
在 Jquery 中使用 JSTL var?有什么解决办法吗?
回答by davidnortonjr
Mixing JSTL code in with the JavaScript can cause your code to become really jumbled. If it's unavoidable, I have all my JSTL variables set to JavaScript variables in one place:
将 JSTL 代码与 JavaScript 混合可能会导致您的代码变得非常混乱。如果不可避免,我会将所有 JSTL 变量都设置在一处:
<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />
<script type="text/javascript">
//NOTE: we are sure 'selectedQuery' does not contain any double-quotes,
// but most values will need to be escaped before doing this.
var selectedQuery = "${selectedQuery}";
// etc.
</script>
...
<script type="text/javascript">
$("#" + selectedQuery + " td input:radio").attr('checked', true);
</script>
回答by Matt Ball
In a JSP:
在 JSP 中:
<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />
<script>
$("#${selectedQuery} td input:radio").attr('checked', true);
</script>
回答by aroth
I do stuff like that all the time. The JSP parser doesn't know or care about the difference between the contents of a <script>
tag (whether using jQuery or not) and any other content in the JSP page.
我一直在做这样的事情。JSP 解析器不知道也不关心<script>
标记的内容(无论是否使用 jQuery)与 JSP 页面中的任何其他内容之间的区别。
It should work fine if you do:
如果您这样做,它应该可以正常工作:
<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />
...
<script>
$("#${selectedQuery} td input:radio").attr('checked', true);
</script>
Note that this requires that the <script>
element with your jQuery selector be inside of the same page/JSP scope as your <c:set>
. If they aren't in the same scope then of course this will not work.
请注意,这要求<script>
带有 jQuery 选择器的元素与<c:set>
. 如果它们不在同一范围内,那么这当然不起作用。