我尝试点击页面中的一个按钮,当我在 Chrome 浏览器上选择检查选项时,我可以在该页面中看到其 ID。正如您从下面看到的,该按钮的 ID 是 troop_confirm_go
。
<input id="troop_confirm_go" style="margin-bottom: 5px" class="troop_confirm_go btn btn-attack" name="submit" type="submit" onload="this.disabled=false;" value="Send Attack">
但是,当我在同一页面上选择查看页面源代码时,我无法在文本中看到该按钮 ID。因此,我认为这就是我无法从代码中访问该按钮以单击它的原因。
这是我的 C# 代码,使用 .Net Framework 4.5:
WebBrowser _wb;
private void PageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if(!IamSureThisIsTheCorrectPage())
return;
var attack = _wb.Document.GetElementById("troop_confirm_go"); // attack is null
attack.InvokeMember("click"); // null reference error
}
如果我可以通过检查看到按钮 ID,我就可以点击它,对吗?我怎样才能实现这个目标?
编辑:这是我单击Inspect
时按钮的父对象。这可能包含我无法访问该按钮的原因的信息。
<form id="command-data-form" action="/game.php?village=39143&screen=place&action=command&h=3447af68" method="post" onsubmit="this.submit.disabled=true;">
.
.
.
<input id="troop_confirm_go" style="margin-bottom: 5px" class="troop_confirm_go btn btn-attack" name="submit" type="submit" onload="this.disabled=false;" value="Saldırı gönder">
<a href="#" id="troop_confirm_train" class="btn btn-img" style="display: none; line-height: 21px">
<img src="https://dstr.innogamescdn.com/8.44.1/28525/graphic/unit/tiny/snob.png" title="" alt="" class=""> Misyoner saldırısı ekle
</a>
</form>
最佳答案
我以前也遇到过一个问题,从您的代码示例来看,尚不清楚,但如果您的按钮位于表单的面板内或另一个控件内,则使用 FindControl( )位于按钮所在的父容器上。 Here是 FindControl() 的 MSDN 页面。
另一种选择可能是为按钮的单击事件添加 JQuery 代码。
这种 JQuery 方法应该适用于动态添加的 DOM 元素或静态 DOM 元素,因此无论您如何将该按钮添加到页面,此函数都应该选择它:
$(function(){
$(document).on('click', '#troop_confirm_go', function(){
$.ajax({
url: '/Controller/MethodName/',
data: null,
type: 'POST',
success: function (ifAnyReturnedData) {
//Your success logic here
}
});
}
};
关于javascript - 使用 "Inspect Element"中的 ID 无法访问按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35835983/