简体   繁体   English

在onclick事件中的javascript函数中传递对象

[英]passing an object in javascript function on onclick event

I am trying to pass an object to a javascript function which should trigger when a link is clicked. 我试图将对象传递给javascript函数,该函数应在单击链接时触发。 But unfortunately I am not able to get it working. 但不幸的是,我无法使其正常运行。

Here is the code on my jsp file for the same: 这是我的jsp文件中相同的代码:

<script type="text/javascript">
    $(document).ready(function() {
        function tryToDoItTwice(obj) {
            var check = obj;
            if(check == null) {
                return true;
            }
            else {
                alert("You're not allowed to do this twice!");
                return false;
            }
        }
    });
</script>

<a href="<c:url value="/somepath" />" onclick="javascript: tryToDoItTwice(${foo});">Try to do it twice</a>

Here foo refers to an object of type Foo . 此处foo表示类型为Foo的对象。

Could someone help me understand what am I doing wrong here? 有人可以帮助我了解我在做什么错吗?

EDIT : Foo is a java object. 编辑Foo是一个Java对象。 and ${foo} is a reference variable referring to Foo java object. ${foo}是引用Foo java对象的引用变量。

Thanks. 谢谢。

Your check variable is locally scoped to that function so it will be redeclared each time the function is called (not storing your value the next time it's clicked. 您的check变量在本地作用于该函数,因此每次调用该函数时都会重新声明它(下次单击时不存储您的值)。

You need to expand the scope of your variable. 您需要扩展变量的范围。

 var check = null;
  $(document).ready(function() {
        function tryToDoItTwice(obj) {
            check = obj;
            if(check == null) {
                return true;
            }
            else {
                alert("You're not allowed to do this twice!");
                return false;
            }
        }
});

Also, if foo exists elsewhere, you probably just want to pass it in like this: 另外,如果foo在其他地方存在,您可能只想像这样传递它:

<a href="<c:url value="/somepath" />" onclick="javascript: tryToDoItTwice(foo);">Try to do it twice</a>

You can't pass a JAVA object directly to javascript. 您不能将JAVA对象直接传递给javascript。 Either you need to return as JSON ( look up GSON or Jackson for converting object to JSON ) or pass variables( not object ) to the function. 您需要作为JSON返回(查找GSON或Jackson以将对象转换为JSON)或将变量(不是object)传递给函数。

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

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