javascript - 在 nativescript 中,On-event 无法从 Gridlayout 获取对象

标签 javascript nativescript

我的代码

var gridLayout = page.getViewById("grid9");
var num;
for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++) {
        num = i * 3 + j;
        //build the grids
        var cell = new StackLayout();
        cell.id = "GD" + num;
        cell.className = "grid";
        cell.on("tap", function () {
            alert(this.id);//  <============problem is here!
        });


        var img = new ImageModule.Image();
        img.src = "~/img/u.png";
        cell.addChild(img);

        GridLayout.setRow(cell, i);
        GridLayout.setColumn(cell, j);
        gridLayout.addChild(cell);
    }
}

该应用程序向我显示了正确的 9 张图片,但在我触摸每条线时提醒我 undefined。 将警报方法参数 this.id 更改为 cell.id 后,如果我点击网格 - 每个网格,它会显示 GD8。 看起来我在点击网格时没有得到单元格对象,或者,加载方法执行后页面上的对象不存在。 我是否以错误的方式使用了 on-event 方法,或者我陷入了 JS 陷阱?

最佳答案

您需要将 args 参数传递给该函数,以便它根据打印出该对象的 ID 来识别您刚刚点击的对象:

cell.on("tap", function(args) {
    alert(args.object.id);
});

关于javascript - 在 nativescript 中,On-event 无法从 Gridlayout 获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39611232/

相关文章:

javascript - 在 React 中强制重新加载 gif

javascript - 获取 0.0200 和 0.120 之间的随机数( float )

java - 无法读取未定义的属性 MyToast.java

listview - 让 Nativescript Telerik UI RadListView 在 Angular 中工作

typescript - VSCode 中的 Nativescript 共享模式总是用错误 "experimental support for decorators..."错误标记类

javascript - cytoscape js 使用 fontawesome 动态更新节点标签

javascript - 在填充对象数组中查找值 mongodb - lodash

javascript - 稍后以 Angular 引用元素

webview - NativeScript:如何禁用 WebView 中的缩放控件?

javascript - 未找到 UI/模板模块 NativeScript