delphi – 如何通过下拉列表中的“value”属性选择项目?

在我的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文档的接口
> AElementID – < select>的ID element(下拉列表的元素ID)
> AOptionValue – 搜索<选项>元素值(下拉列表项的值)

返回值:

如果<选项>如果成功找到(并选中)给定值,则返回值是指定下拉列表中该选项的索引,否则为-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>

相关文章

 从网上看到《Delphi API HOOK完全说明》这篇文章,基本上都...
  从网上看到《Delphi API HOOK完全说明》这篇文章,基本上...
ffmpeg 是一套强大的开源的多媒体库 一般都是用 c/c+&#x...
32位CPU所含有的寄存器有:4个数据寄存器(EAX、EBX、ECX和ED...
1 mov dst, src dst是目的操作数,src是源操作数,指令实现的...