delphi – 如何通过下拉列表中的“value”属性选择项目?
发布时间:2020-12-15 10:04:10 所属栏目:大数据 来源:网络整理
导读:在我的Delphi应用程序中,我使用的是TWebBrowser控件,我在其中加载了一个HTML文档,其中包含 select元素(下拉列表),其中包含一些 option items(下拉列表项).假设我在Web浏览器中加载了以下HTML文档: htmlbody select id="ComboBox" option value="firstvalue"
在我的Delphi应用程序中,我使用的是TWebBrowser控件,我在其中加载了一个HTML文档,其中包含< select>元素(下拉列表),其中包含一些< option> items(下拉列表项).假设我在Web浏览器中加载了以下HTML文档:
<html> <body> <select id="ComboBox"> <option value="firstvalue">First Value</option> <option value="secondvalue">Second Value</option> <option value="thirdvalue">Third Value</option> </select> </body> </html> 我如何以编程方式选择例如< option>,其value属性是thirdvalue?或者换句话说,当我只知道此项的值属性是第三个值时,如何以编程方式选择此下拉列表中的第三个项目? 解决方法
例如,您可以将
IHTMLSelectElement 接口与其
selectedIndex 属性一起使用.作为一个展示我已经做了以下功能.
SelectOptionByValue函数 以下函数尝试查找并选择(如果找到)< option> (指定< select>)中给定值属性值的(下拉列表项)元素(下拉列表).如果没有<选项>如果找到,则清除当前下拉列表选择(未选择任何项目). 参数: > ADocument – 输入HTML文档的接口 返回值: 如果<选项>如果成功找到(并选中)给定值,则返回值是指定下拉列表中该选项的索引,否则为-1. 源代码: function SelectOptionByValue(const ADocument: IDispatch; const AElementID,AOptionValue: WideString): Integer; var HTMLDocument: IHTMLDocument3; HTMLElement: IHTMLSelectElement; function IndexOfValue(const AHTMLElement: IHTMLSelectElement; const AValue: WideString): Integer; var I: Integer; begin Result := -1; for I := 0 to AHTMLElement.length - 1 do if (AHTMLElement.item(I,I) as IHTMLOptionElement).value = AValue then begin Result := I; Break; end; end; begin Result := -1; if Supports(ADocument,IID_IHTMLDocument3,HTMLDocument) then begin if Supports(HTMLDocument.getElementById(AElementID),IID_IHTMLSelectElement,HTMLElement) then begin Result := IndexOfValue(HTMLElement,AOptionValue); HTMLElement.selectedIndex := Result; end; end; end; 用法示例: 要从HTML文档的下拉列表中选择具有第三值的项目,可以使用此代码(假设在WebBrowser1组件中加载了该文档): procedure TForm1.Button1Click(Sender: TObject); var Index: Integer; begin Index := SelectOptionByValue(WebBrowser1.Document,'ComboBox','thirdvalue'); if Index <> -1 then ShowMessage('Option was found and selected on index: ' + IntToStr(Index)) else ShowMessage('Option was not found or the function failed (probably due to ' + 'invalid input document)!'); end; 来自问题的示例HTML文档: <html> <body> <select id="ComboBox"> <option value="firstvalue">First Value</option> <option value="secondvalue">Second Value</option> <option value="thirdvalue">Third Value</option> </select> </body> </html> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |