使用“检查元素”中的 id 无法访问按钮

Button not reachable using the id from "Inspect Element"

本文关键字:id 访问 按钮 中的 检查 元素 检查元素 使用      更新时间:2023-09-26

我正在尝试单击页面中的按钮,当我在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。因此,我认为这就是我无法从代码中访问按钮以单击它的原因。

这是我使用 .Net Framework 4.5 的 C# 代码:

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() 可能会很有用。 下面是 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
        }
    });
    }
};

WebBrowser对象加载正确的 DOM 没有问题。这完全是我的错。我无法加载正确的网址。

感谢您的帮助monstertjie_za