Javascript 在jsp中运行javascript函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32798444/
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
running javascript function inside jsp
提问by JonCode
Is it possible to run javascript functions inside jsp tags? I'd like to run a sudden function as many times as there's objects in my ArrayList. Below doesen't work, but I hope it gives an idea of what I'm trying to achieve.
是否可以在 jsp 标签内运行 javascript 函数?我想像 ArrayList 中的对象一样多次运行一个突然的函数。下面不起作用,但我希望它可以让我了解我正在努力实现的目标。
<script>
function test(){
alert();
}
</scripts>
<%
ArrayList<Marker> list = new ArrayList<Marker>();
list = (ArrayList<Marker>)request.getAttribute("markers");
for(int i = 0; i < list.size(); i++){
%>
<script>
<%
test();
%>
</script>
<%
}
%>
Is it possible to do it with something like ?
有没有可能用类似的东西来做?
<c:forEach var="name" items="${markers}">
<%-- call my javascript function --%>
</c:forEach>
回答by Murli
Below correction in your code will work fine for you
您的代码中的以下更正对您来说可以正常工作
<script>
function test(){
alert("Hello"); // added sample text
}
</script>
<%
ArrayList<Marker> list = new ArrayList<Marker>();
list = (ArrayList<Marker>)request.getAttribute("markers");
for(int i = 0; i < list.size(); i++){
%>
<script>
test(); //No need to put java script code inside scriptlet
</script>
<%
}
%>
回答by Luka Govedi?
<%
ArrayList<Marker> list = new ArrayList<Marker>();
list = (ArrayList<Marker>)request.getAttribute("house");
for(int i = 0; i < list.size(); i++){
%>
<script>
test('<%= list.get(i).name %>');
<script>
<%
}
%>
<script>
function test(i){
alert(i);
}
</script>
回答by Ashutosh K Singh
By writing your js code within the script tag inside a out.println() has shown below:
通过在 out.println() 内的 script 标签中编写您的 js 代码,如下所示:
<%
ArrayList<Marker> list = new ArrayList<Marker>();
list = (ArrayList<Marker>)request.getAttribute("markers");
for(int i = 0; i < list.size(); i++){
out.println("<script>test();</script>");
}
%>