7238 次
1 に答える
10
IHTMLSelectElement
たとえば、インターフェイスをそのselectedIndex
プロパティで使用できます。ショーケースとして、次の関数を作成しました。
SelectOptionByValue 関数
次の関数は、指定された要素 (ドロップダウン リスト)内の特定の属性値<option>
の (ドロップダウン リスト項目)を検索し、選択 (見つかった場合) しようとします。noが見つかった場合、現在のドロップダウン リストの選択はクリアされます (項目は選択されません)。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;
使用例:
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;
質問の 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>
于 2012-10-13T18:32:35.927 に答える