javascript - 使用 "Inspect Element"中的 ID 无法访问按钮

标签 javascript c# html webbrowser-control

我尝试点击页面中的一个按钮,当我在 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&amp;screen=place&amp;action=command&amp;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/

相关文章:

javascript - 无法监听文档调整大小事件

c# - 如何更新 TabControl 资源?

c# - 跨平台 C# - System.io 和其他怪癖

c# - autofac 的 Func<T> 解析命名服务

javascript - Img 充当 HTML 表单中不应该提交的按钮

javascript - jQuery 点击函数 - 获取这个的 ID

javascript - 如何循环本地存储以匹配登录输入

javascript - jquery动画编号从到

java - 使用 JSoup 解析特定元素

javascript - 将 Canvas 图像数据中的像素更改为 hsl(60, 100%, 50%)