开发者

variable input to javascript function parameter within a JSP page

I have the following function call inside a jsp page.

jQuery(function($){
   $("#product").mask("99/99/9999",{placeholder:" "});
});

What I want to do is pass a different string into the .mask function. In pseudo code it would look something along the lines of:

String passedParam= someString  
if(test):
  passedParam = "someotherString"

jQuery(function($){
   $("#product").mask(passedParam,{p开发者_Python百科laceholder:" "});
});

Being new to both jsp and javascript I do not know the correct way to translate this pseudo code into actual working code.


You can use taglibs/EL in JSP to print a string as if it's JavaScript code. You know, JSP runs at webserver machine, produces HTML/CSS/JS and sends it to the webbrowser which in turn starts to run JS code. You should write server side code accordingly that its HTML/CSS/JS output looks right when you're doing View Source in webbrowser.

Your pseudocode is a bit ambiguous, but I bet that you're looking for something like this:

jQuery(function($){
   $("#product").mask('${test ? 'someotherString' : mask}',{placeholder:" "});
});

(don't pay attention to syntax highlighting, the code is correct, the highlighter doesn't recognize EL)

The ${} thing is EL (Expression Language). It will be processed when JSP runs. It should work in template text as per Servlet 2.4/JSP 2.0 (which is already over 5 years old). The ?: is the well known conditional operator. If the expression evaluates true, then the part after ? will be assigned/printed (in this case the literal string "someotherString"), otherwise the part after the : (in this case the scoped variable mask).

This will end up in the webbrowser as

jQuery(function($){
   $("#product").mask('someotherString',{placeholder:" "});
});

or

jQuery(function($){
   $("#product").mask('someString',{placeholder:" "});
});

depending on the boolean outcome of test.


Well in my jsp I would do something like this:

<%
String mask = someString  
if(test):
  mask = "someotherString"
%>

jQuery(function($){
   $("#product").mask(<%= mask %>,{placeholder:" "});
});


Handle the mask variable using JSP, then put it inside jQuery code.

<%
   String mask = "";
   if (test) {
       mask = "something";
   }
   else {
       mask = "something else";
   }
%>

jQuery(function($){
   $("#product").mask('<%=mask%>',{placeholder:" "});
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜