2016-07-30 24 views
1

定位的合金元素是易與如何在Appcelerator中動態定位UI元素?

views.xml:

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

controller.js:

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

但有一種動態傳遞目標ID到一個函數並設置這個函數的值?特別是,我想改變最後選擇的對象的背景顏色。

比如像:

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語句。這當然非常麻煩。

回答

2

在你的情況下,你可以使用 selectedObject = e.source沒有ID。然後你的變量裏面有整個對象。在changeBackgroundColor裏面你可以使用沒有$的id。

例如這個作品:

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()作爲參數即可。取決於你的使用案例

+0

完美!謝謝! – user24957