c#浏览器在表单中点击单选按钮
本文关键字:单选按钮 表单 浏览器 | 更新日期: 2023-09-27 18:11:07
我在我的代码中使用webbrowser元素来自动化一些东西。我在这个浏览器中加载一个表单,其中包含几个单选按钮。我的目的只是选择一个单选按钮。然而,在html代码中,有一个JS代码根据所选的单选按钮改变表单操作目标。如果我输入
webBrowser1.Document.GetElementById("chicken").SetAttribute("checked", "checked");
它选择了我想要的单选按钮。我的意思是它不会触发JS代码。在这段JS代码中,它也提交了页面,所以我上面的代码只选择单选按钮并调用同一页面。我怎么解决这个问题?
表单标签如下:
<form id="choose_dept" method="POST" action="/place/">
JS代码是这样的:
<script type="text/javascript">
<!--
$("#choose_dept").change(function(){
$("#choose_dept").attr('action', '/place/' + ('input[name=department]:checked').val()
+ '/' );
this.submit();
});
- ->
去年编辑: String sc = @"$(document).ready(function(){" +
"$('"input:radio[name=department]'").change(function() {" +
"$('"#choose_dept'").attr('action','place/'+$(this).val());" +
"$('"#choose_dept'").submit();" +
"});" +
"});";
HtmlElement headElem = (HtmlElement)webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElem = (HtmlElement)webBrowser1.Document.CreateElement("script");
IHTMLScriptElement elem = (IHTMLScriptElement)scriptElem.DomElement;
elem.text = sc;
headElem.AppendChild(scriptElem);
webBrowser1.Document.GetElementById("chicken").SetAttribute("checked", "checked");
webBrowser1.Document.InvokeScript("ready()");
我认为在你的情况下比c#代码你的问题是你的jquery代码。试试下面的代码:
$(document).ready(function(){
$("input:radio[name=department]").change(function() {
$("#choose_dept").attr('action','place/'+$(this).val());
$("#choose_dept").submit();
});
});
编辑:(既然你提到你无法控制HTML代码,那么你可以在飞行中添加JavaScript,我刚刚向你展示的代码如下:
String sc = @"$(document).ready(function(){
$("input:radio[name=department]").change(function() {
$("#choose_dept").attr('action','place/'+$(this).val());
$("#choose_dept").submit();
});
});";
var doc = webBrowser1.Document;
var headElem = (HtmlElement) doc.GetElementsByTagName("head")[0];
var scriptElem = (HtmlElement) doc.CreateElement("script");
var elem = (IHTMLScriptElement)scriptElem.DomElement;
elem.text = sc;
headElem.AppendChild(scriptElem);
但是,您需要添加Reference
Microsoft.mshtml
你需要在你的代码的顶部添加
using mshtml;
现在,如果你不想在飞行中改变它,你真的只想调用javascript方法,那么你可以使用下面的:
webBrowser1.Document.InvokeScript("methodnamehere()");
基于您的代码的最新编辑:
我认为你需要在你的浏览器中模拟点击,一旦你选中了你的单选按钮。所以,它现在是这样的:
String sc = @"$(document).ready(function(){" +
"$('"input:radio[name=department]'").change(function() {" +
"$('"#choose_dept'").attr('action','place/'+$(this).val());" +
"$('"#choose_dept'").submit();" +
"});" +
"});";
HtmlElement headElem = (HtmlElement)webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElem = (HtmlElement)webBrowser1.Document.CreateElement("script");
IHTMLScriptElement elem = (IHTMLScriptElement)scriptElem.DomElement;
elem.text = sc;
headElem.AppendChild(scriptElem);
webBrowser1.Document.GetElementById("chicken").SetAttribute("checked", "checked");
HtmlElement simulateClick = webBrowser1.Document.GetElementById("chicken");
simulateClick.InvokeMember("click");
try
webBrowser1.Document.GetElementById("chicken").RaiseEvent("onchange");