如何通过<select>下拉列表中的"value"属性选择<option>项?

yar*_*rek 6 delphi dom twebbrowser

在我的Delphi应用程序中,我正在使用一个TWebBrowser控件,我在其中加载了一个HTML文档,其中包含一个<select>元素(下拉列表)和一些<option>项目(下拉列表项).假设我在网络浏览器中加载了以下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>
Run Code Online (Sandbox Code Playgroud)

我怎样才能以编程方式选择,例如<option>,其value属性是thirdvalue?或者换句话说,当我只知道该项的value属性是thirdvalue什么时,我如何以编程方式选择此下拉列表中的第三项?

TLa*_*ama 10

例如,您可以将IHTMLSelectElement接口与其selectedIndex属性一起使用.作为展示,我做了以下功能.

SelectOptionByValue函数

以下函数尝试查找并选择(如果找到)指定元素(下拉列表)中<option>给定value属性值的<select>(下拉列表项).如果未<option>找到,则清除当前下拉列表选择(未选择任何项目).

参数:

  • ADocument - 输入HTML文档的接口
  • AElementID - <select>元素的ID(下拉列表的元素ID)
  • AOptionValue - 搜索的<option>元素值(下拉列表项的值)

返回值:

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

用法示例:

要从thirdvalue问题的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;
Run Code Online (Sandbox Code Playgroud)

来自问题的示例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>
Run Code Online (Sandbox Code Playgroud)

  • [+1]由于你包括`if Supports`,HTMLElement可能不是'IHTMLSelectElement`所以我会使用:`if Supports(HTMLDocument.getElementById('ComboBox'),IID_IHTMLSelectElement,HTMLElement)then ...`.只是我的2美分;) (3认同)