如何在Appcelerator中动态定位UI元素?

时间:2016-07-30 08:37:33

标签: titanium-alloy appcelerator-titanium

使用

轻松定位Alloy元素

views.xml:

<Label id="targetID1"/>
<Label id="targetID2"/>
<Label id="targetID3"/>

controller.js:

$.targetID1.backgroundColor = "red";
$.targetID2.backgroundColor = "green";
$.targetID3.backgroundColor = "blue";

但有没有办法动态地将目标ID传递给函数并在此函数中设置值?特别是,我想更改最后一个选定对象的背景颜色。< / p>

例如:

var selectedObject;

function clickOnObject(e) {
selectedObject = e.source.id;
return selectedObject;
}

changeBackgroundColor(selectedObject)

//should change the background color of the selected object passed to the function

function changeBackgroundColor(id) {
    $.id.backgroundColor = "orange" //this does not work
}

我发现了这个(Select dynamically generated element by id in Titanium Appcelerator),但我不确定这是不是一回事。

我有多个字段并使用了switch语句。这当然非常麻烦。

1 个答案:

答案 0 :(得分:2)

在你的情况下你可以使用 没有ID的selectedObject = e.source。然后你在变量中包含整个对象。在changeBackgroundColor中你将使用没有$。的<。

e.g。这有效:

var obj;

function fn(){
    obj.title = "testasdf"
}

$.btn1.addEventListener("click",function(e){
    obj = e.source;
    fn();

});
$.btn2.addEventListener("click",function(e){
    obj = e.source;
    fn();
});

在index.xml中创建了两个按钮。但是你可以在没有var obj的情况下使用它,只需将e.source传递给fn()作为参数。取决于您的用例

相关问题