简体   繁体   中英

change background color of view by its ID in Titanium

I have several views that are added to a ScrollView dynamically with a for, but when the user clicks on one of the views, I want to change the Background color of the view. I have the following code for the click event:

(function() {
    var id = i;
    viewQuantity.addEventListener('click', function(e) {
        viewQuantity.backgroundColor = '#FFFFFF';
    });
})(); 

but with this code the view that changes the color is always the last added view. How can I use the id to change the view that was clicked by the user?

Within a click event you get an event property in the function as first parameter. This has source object which is the element the user has clicked.

var clickedView;
(function() {
    var id = i;
    viewQuantity.addEventListener('click', function(e) {
        if (clickedView){
             clickedView.backgroundColor= '#000000'; // put your own color here to restore original
        }
        e.source.backgroundColor = '#FFFFFF';
        clickedView = e.source;
    });
})(); 

To change the color later, you can store a reference to the object, and change the color later

Try something like this:

var scrollView = Ti.UI.createScrollView();

var lastClickedView;

for(var i = 0;i<=10;i++){
    (function(){
        var view = Ti.UI.createView();
        var label = Ti.UI.createLabel();
        view.add(label);
        scrollView.add(view);
        view.addEventListener('click',function(){
            if(lastClickedView){
                lastClickedView.backgroundColor = '#000';
                lastClickedView.children[0].color = '#000';
            }
            view.backgroundColor = '#fff';
            label.color = '#fff';
            lastClickedView = view;
        });
    })();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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