简体   繁体   English

通过钛中的ID更改视图的背景色

[英]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. 我有几个视图,它们通过for动态添加到ScrollView中,但是当用户单击其中一个视图时,我想更改视图的背景颜色。 I have the following code for the click event: 我为click事件提供了以下代码:

(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? 如何使用ID更改用户单击的视图?

Within a click event you get an event property in the function as first parameter. 在click事件中,您将在函数中获得一个event属性作为第一个参数。 This has source object which is the element the user has clicked. 它具有source对象,即用户单击的元素。

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;
        });
    })();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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