单击文本字段中的行时AS3调用函数

时间:2014-07-30 12:58:12

标签: string actionscript-3 function line textfield

如果点击TextField / TextArea中的一行文字,您如何调用其他函数?

我已经有一个函数可以在单击TextField的任何一点时检索描述:

list.text = "chicken";
list.addEventListener(MouseEvent.CLICK, getter);

var descriptionArray:Array = new Array();
descriptionArray[0] = ["potato","chicken","lemon"];//words
descriptionArray[1] = ["Round and Brown","Used to be alive","Yellow"];//descriptions

function getter(e:MouseEvent):void
{

    for (var i:int = 0; i < descriptionArray.length; i++)
    {
        var str:String = e.target.text;//The text from the list textfield
        if (str == descriptionArray[0][i]) //if the text from List is in the array
        {
            trace("found it at index: " + i);
            description.text = descriptionArray[1][i];//displays "Used to be alive".
        }
        else
        {
            trace(str+" != "+descriptionArray[0][i]);
        }
    }
}

它工作正常,并返回正确的描述。

但是我希望它根据单击TextField / TextArea中的哪一行来检索不同的描述,例如,如果我使用list.text = "chicken\npotato"

我知道我可以使用多个文本字段来包含每个单词,但列表可能包含超过100个单词,我想使用TextArea的滚动条滚动列表中的单词,如果我使用多个文本字段/区域,每个人都有自己的滚动条,这是毫无意义的。

那么,如何根据我点击的哪一行调用不同的函数?

PS:从技术上来说,它不是一个不同的功能,它正在检测被点击的行中的字符串,我只是把它放在最小的混乱中。

1 个答案:

答案 0 :(得分:1)

有一些内置方法可以让您的生活更轻松:

function getter(e:MouseEvent):void
{
    // find the line index at the clicked point
    var lineIndex:int = list.getLineIndexAtPoint(e.localX, e.localY);
    // get the text at that line index
    var itemText:String = list.getLineText(lineIndex).split("\n").join("").split("\r").join("");

    // find the text in the first array (using indexOf instead of looping)
    var itemIndex:int = descriptionArray[0].indexOf(itemText);

    // if the item was found, you can use the sam index to 
    // look up the description in the second array
    if(itemIndex != -1)
    {
        description.text = descriptionArray[1][itemIndex];
    }
}
相关问题