我使用下面的代码搜索文本区域中的文本,以查找在textinput中输入的字符串。我试图突出显示字符串在文本区域后,它已被搜索。我假设这个方法是selectRange()
。我不确定如何找到selectRange()
的第二个参数的endIndex。下面是我写的:
protected function searchBtn_clickHandler(event:MouseEvent):void
{
text = mainTextField.text;
search_Str = searchTxt.text;
var search_result:int = text.search(search_Str);
trace(search_result);
编辑
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:titleContent>
<s:TextInput id="searchTxt"/>
<s:Button label="Button" click="searchBtn_clickHandler(event)"/>
</s:titleContent>
<s:TextArea id="mainTextField" x="33" y="35" width="544" height="444"/>
<fx:Script>
<![CDATA[
public var text:String;
public var search_Str:String;
protected function searchBtn_clickHandler(event:MouseEvent):void
{
text = mainTextField.text;
search_Str = searchTxt.text;
var search_result:int = text.search(search_Str);
trace(search_result); // Traces correct int values
trace(mainTextField.selectRange(search_result,search_result+search_Str.length)); // Traces "undefined"
}
]]>
</fx:Script>
</s:View>
你不能根据搜索字符串的长度来计算吗?
修改后的代码是这样的:
protected function searchBtn_clickHandler(event:MouseEvent):void
{
text = mainTextField.text;
search_Str = searchTxt.text;
var search_result:int = text.search(search_Str);
trace(search_result);
mainTextField.selectRange(search_result,search_result+search_Str.length);
}
更新,响应原海报的代码更新;我进行了测试。如果没有焦点,TextAre将不会显示选中的项目。因此,要使所选范围突出显示,解决方案是在单击按钮后将焦点设置为textArea。下面是演示这一点的代码:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:titleContent>
<s:TextInput id="searchTxt" text="Quick" />
<s:Button label="Button" click="searchBtn_clickHandler(event)"/>
</s:titleContent>
<s:TextArea id="mainTextField" x="33" y="35" width="544" height="444" text="The Quick Brown Fox Jumped Over The Lazy Dogs"/>
<fx:Script>
<![CDATA[
public var text:String;
public var search_Str:String;
protected function searchBtn_clickHandler(event:MouseEvent):void
{
mainTextField.setFocus();
text = mainTextField.text;
search_Str = searchTxt.text;
var search_result:int = text.search(search_Str);
trace(search_result); // Traces correct int values
trace(search_result+search_Str.length);
// trace(mainTextField.selectRange(search_result,search_result+search_Str.length)); // Traces "undefined"
mainTextField.selectRange(search_result,search_result+search_Str.length)
}
]]>
</fx:Script>
</s:View>