【问题标题】:Modify below function to select item from dropdown修改以下函数以从下拉列表中选择项目
【发布时间】:2013-07-19 13:07:51
【问题描述】:

我有以下 Delphi 代码可以在 TWebBrowser 上填写表单:

procedure SetFieldValue(theForm: IHTMLFormElement; const fieldName: string; const newValue: string);
   var
     field: IHTMLElement;
     inputField: IHTMLInputElement;
     selectField: IHTMLSelectElement;
    textField: IHTMLTextAreaElement;
begin
  field := theForm.Item(fieldName, '') as IHTMLElement;
  if Assigned(field) then
  begin
    if field.tagName = 'INPUT' then
    begin
      inputField := field as IHTMLInputElement;
      // Make the change below to catch checks and radios.
      if (inputField.type_ = 'checkbox') or (inputField.type_ = 'radio') then
      begin
        if newValue = 'Y' then
          inputField.checked := True
        else
          inputField.checked := False;
      end
      else
        inputField.value := newValue;
    end
    else if field.tagName = 'SELECT' then
    begin
      selectField := field as IHTMLSelectElement;
      selectField.value := newValue;
    end
    else if field.tagName = 'TEXTAREA' then
    begin
      textField := field as IHTMLTextAreaElement;
      textField.value := newValue;
    end;
  end;
end;

HTML 源代码类似于以下示例:

<select name="xosid">
   <option value="" selected>-- choose one --</option>
   <option value="first">This is one</option>
   <option value="second">Another</option>
</select>

我想修改上述函数,以便能够在不知道值的情况下从下拉列表中选择“另一个”...

有什么建议吗?

提前致谢,

Zsolt

【问题讨论】:

  • 你的意思是你想通过索引选择&lt;option&gt;,或者通过它的文本
  • 这里有select &lt;option&gt; by textselect &lt;option&gt; by value,如果你简化后者,你会得到索引选择。
  • 我想根据文字选择
  • 那么您可能正在寻找code like this。我已经使用 tagName 属性改进了这个非常不安全的部分。
  • 感谢 TLama,再次需要这个,并找到了您的代码提示 :)

标签: html delphi twebbrowser


【解决方案1】:

能够在不知道值的情况下从下拉列表中选择“另一个”

那么按索引呢?选项编号 2(从零开始)?

让我们从searching for data type in Google开始

第一个链接是MSDN specifications for that datatype in Microsoft Internet Explorer。在右侧您可以看到selectedIndex: Integer 属性。

所以代码会是这样的

else if field.tagName = 'SELECT' then
    begin
      selectField := field as IHTMLSelectElement;
      selectField.selectedIndex := 2;
    end

回到 Google,我的第三个链接是使用该属性的准备好的 source code example

【讨论】:

  • 不要依赖tagName,而是使用例如var SelectElement: IHTMLSelectElement; begin ... if Supports(field, IID_IHTMLSelectElement, SelectElement) then....
  • @Tlama - 这是给 topicstarter 而不是我的
【解决方案2】:
    selectField.value := (selectField.item(selectField.length-1,EmptyParam) as IHTMLOptionElement).value;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    相关资源
    最近更新 更多