【问题标题】:Why Object's properties get undefined when pass through as paramters为什么当作为参数传递时对象的属性会变得未定义
【发布时间】:2014-02-07 10:27:57
【问题描述】:

为什么在这个 JavaScript 方法中传递参数会导致它的属性未定义,这是我目前正在尝试的,

    $.each(data.GetSomeRestMethodResult, function (index, item) {
            $("#sTable").append(AnotherMethods(item.a, item.b, item.c));
        });

    function AnotherMethods(a, b, c) {
        alert(a +" - "+ b +" - "+ c);
        var r = "<tr class='Row' onclick='LoadDetails(" + a + b + c ")'></tr>"
    }

现在,如果我使用 chrome 源和调试,项目具有所有值,但是当我查看子函数中的参数时,它们都是未定义的 :(

编辑

修复了这个问题,因为 WCF Web 服务正在发送特定类型对象的数组(我自己更改了它,但忘记更新 JS)但是下面对我有用,

    $.each(data.GetSomeRestMethodResult.TYPEOFOBJECT, function (index, item) {
            $("#sTable").append(AnotherMethods(item.a, item.b, item.c));
        });

    function AnotherMethods(a, b, c) {
        alert(a +" - "+ b +" - "+ c);
        var r = "<tr class='Row' onclick='LoadDetails(" + a + b + c ")'></tr>"
    }

以上代码是手写的,抱歉我无法发布所有代码,因为它太多了@webservices,完整的js文件等。

【问题讨论】:

  • 它没有。发布minimal, complete example demonstrating the problem you're having。以上将正常工作。如果item 确实具有abc 属性,则它们的值将传递给AnotherMethods。 (旁注:您使用的是AnotherMethods 的返回值,但它不返回任何内容。)
  • @T.J.Crowder 谢谢,马上修改代码并尽快发布
  • @yaron 请考虑了解有关 jQueri API 的更多信息。 onclick 可能不应该存在(使用 .click 代替)-此外,您可能不想混合数据和演示文稿。
  • @BenjaminGruenbaum 感谢您的建议,现在将在我的代码中实现它。

标签: jquery json rest


【解决方案1】:

(根据您的更新更新)

问题是您使用了AnotherMethods 的返回值(将返回值传递给append),但AnotherMethods 实际上并没有返回任何内容。它只是创建了一个变量r。您还有一个语法错误(c 之后缺少+)。

这行得通,例如:

$.each(data.GetSomeRestMethodResult, function (index, item) {
  $("#sTable").append(AnotherMethods(item.a, item.b, item.c));
});

function AnotherMethods(a, b, c) {
  return "<tr class='Row' onclick='LoadDetails(" + a + b + c + ")'><td>Row for " + a + ", " + b + ", " + c + "</td></tr>";
}

Live Copy | Source

【讨论】:

  • 这实际上看起来非常接近实际问题。查看更新(他想返回一个r 变量)。
  • @BenjaminGruenbaum:感谢您指出 Q 已更新。是的,你是对的,仍然没有返回任何东西(和语法错误)。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 2020-04-14
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多