简体   繁体   English

从JSP页面调用Java Script函数不返回值

[英]Calling Java Script function from JSP page not returning value

I have written a java script function which will return Language name based on code passed to the function as argument. 我已经编写了一个Java脚本函数,它将基于传递给函数作为参数的代码返回语言名称。

I am getting code from the servlet as response. 我从servlet获取代码作为响应。 I tried in the following way: 我尝试了以下方式:

----
</fieldset>
    <fieldset class = "field">
        <legend>Language</legend>
        <table border = '0'>
            <tr>
                <td>Spoken:</td>
                <!-- <td><input type = "text" name = "FirstName"  value = "${spoken}"/></td> -->
                <td><input type = "text" name = "spoken"  value = getLanguage(${spoken}) /></td>
            </tr>
            <tr>
                <td>Written:</td>
                <td><input type = "text" name = "written"  value = "${written}"/></td>
            </tr>
        </table>

</fieldset>
----

Java script function: Java脚本功能:

<script>
function getLanguage(code) {
    if(code.equals("EN"))
        return "ENGLISH";
    else if(code.equals("SP"))
        return "SPANISH";
    else
        return "";
}
</script>    

But in output instead of displaying language I am getting function call displayed. 但是在输出而不是显示语言中,我正在显示函数调用。 Can someone tell me what is happening wrong here? 有人可以告诉我这是怎么回事吗?

Maybe you can't do like this. 也许你不能这样。 You will be passing code to js function and then inside a js function you can dom manipulation. 您将代码传递给js函数,然后在js函数内部可以进行dom操作。 Like that; 像那样;

<script>
function setLanguage(code, elementId) {
    if(code.equals("EN"))
        document.getElementsByTagId(elementId).val = "ENGLISH";
    else if(code.equals("SP"))
        document.getElementsByTagId(elementId).val = "SPANISH";
    else
        document.getElementsByTagId(elementId).val = "Unknow";
}
</script>    

You need to place calls to javascript function between <script> and </script> . 您需要在<script></script>之间放置对javascript函数的调用。

There could be several ways of solving this. 可能有几种解决方法。 One solution is as follows: 一种解决方案如下:

In your html, use 在您的html中,使用

<input type = "text" name = "FirstName"  data-value = "${spoken}"/>

Note how data-value attribute holds the value of spoken . 注意data-value属性如何保持spoken的价值。

Then have the following <script> block after getLanguage() is defined: 定义getLanguage() 之后,具有以下<script>块:

<script>

(function() {
  var input = document.querySelector('input[name=FirstName]')[0];
  var code = input.getAttribute('data-value');
  input.setAttribute('value', getLanguage(code));

})();

</script>

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

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