我正在使用下面的代码在textarea中搜索textInput中输入的字符串。我正在尝试在搜索之后突出显示textarea中的字符串。我假设这样做的方法是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>
答案 0 :(得分:2)
你不能根据搜索字符串的长度来计算它吗?
修改后的代码如下:
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>