搜索框 as3 无法正常工作

searchbox as3 not working properly

我有一个问题,无论我输入什么文本,甚至是空白 space,我仍然进入第 170 帧,如你所见,我在那里输入 171 帧,如果我输入 "therefore",它就会进入171,看起来它工作正常,即使我输入了错误的文本,它也会转到第 170 帧,但我找不到问题,我也不知道我是否应该做一个 else 语句,所以如果这个词不在列表中,它就会去到其他框架,谢谢队友

 var i:int = 0;
var names:Array = new Array("therefore","disciples","nations","baptizing","father","son","holy spirit");
var frames:Array = new Array("171","170","170","170","170","170","170","170");

button_140.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_4);

function fl_MouseClickHandler_4(event:MouseEvent):void
{
var searchtext:String = searchtext.text.toLowerCase();
findInArray(searchtext);
gotoAndStop(frames[i]);
}

function findInArray(str:String):int
{
for(i=0; i < names.length; i++)
{

        if(names[i] == str)
        {
    return i;
}
}
return 0;
}

为什么你总是转到第 170 帧:

让我们看看你的函数fl_MouseClickHandler_4:

findInArray(searchtext);//string won't be found so "i" would be 7 (the last index in array)
gotoAndStop(frames[i]);//so it goes to frame 170

针对您的代码的修复:
函数 fl_MouseClickHandler_4:

function fl_MouseClickHandler_4(event:MouseEvent):void
{
var searchtext:String = searchtext.text.toLowerCase();
var index:int=findInArray(searchtext);

if(index==-1){
    //do something when frame not found
}
else{
    gotoAndStop(frames[index]);
}

函数findInArray

function findInArray(str:String):int
{
for(i=0; i < names.length; i++)
{

    if(names[i] == str)
    {
return i;//return the found index
}
}
return -1;//return -1 if nothing found
}

希望对您有所帮助...

编辑:

您不需要创建函数来查找数组中的值。您可以使用 Array class 内置方法 indexOf() 查找数组中某项的索引:有关详细信息,请参阅 AS3 manual

theArray.indexOf(theValue);

returns 值的索引。如果 theValue 不在 theArray 中,returns -1.

在下面测试这个例子:

//# declare variables outside of function (make once & re-use) 
var searchtext:String = "";
var index:int = 0; 

//# after updating searchtext string with user-text then run function below

function fl_MouseClickHandler_4(event:MouseEvent):void
{
    searchtext = searchtext.text.toLowerCase();
    index = names.indexOf(searchtext); //test with "holy spirit"

    if(index == -1)
    {
        trace("index is : -1 : No match found");
        //do something when frame not found
    }
    else
    {
        trace("index is : " + index + " ::: result is : " + (frames[index]) );
        gotoAndStop( frames[index] );
    }
}