伙计们!我必须通过win forms应用程序中的代码自动设置一些字段值,该应用程序包含一个web浏览器。唯一不起作用的是在multiselect中设置值。我可以通过代码点击按钮,设置文本框字段等,但是多选列表不起作用(不能正确设置值)。首先,这是该元素在页面中的HTML代码:
<select size="10" name="someName" multiple="multiple" onchange="javascript:setTimeout('someFunc')" id="elementId" showconfirmedonly="true" showextraitems="true">
<option selected="selected" value="1">First opt</option>
<option value="2">Second opt</option>
<option value="3">Third opt</option>
<...other options...>
</select>
我尝试先取消选择所有元素,方法如下:
webBrowser.Document.GetElementById(elementId).InnerHtml =
webBrowser.Document.GetElementById(elementId).InnerHtml.Replace(
"<option selected=\"selected\"", "<option");
然后我尝试以这种方式选择(只有一个)所需的元素(值):
webBrowser.Document.GetElementById(elementIWantToSelectId).Focus();
element.SetAttribute("selected", "selected");
webBrowser.Document.GetElementById(elementIWantToSelectId).InvokeMember("onchange");
首先,我必须取消选择所选的选项,然后选择我想要的单个选项。如果我只尝试用Replace方法更改html,它不能工作,也不能只设置选定的属性。页面中的其他字段会随着任何值的改变而改变(当onchange func被调用时-我必须在任何地方设置值时调用它),这就是为什么我必须调用'onchange‘函数。当代码执行时,所有的选项都消失了,多选框是空的,我发现这真的很奇怪。任何如何解决我的问题的建议都将不胜感激。
发布于 2019-06-06 02:52:42
忘了替换业务吧。
您需要做的是设置"select
“HtmlElemnt
的"value
”属性(不要弄乱任何"option
“HtmlElement
)
webBrowser.Document.GetElementById(elementId).SetAttribute("value", "1");
发布于 2015-07-17 08:25:38
您可以使用jQuery/ javascript完成此操作
此示例代码片段可能会对您有所帮助。
$("select option").each(function(){
if ($(this).text() == "B")
$(this).attr("selected","selected");
});
https://stackoverflow.com/questions/31470416
复制