【问题标题】:Button not reachable using the id from "Inspect Element"使用“检查元素”中的 ID 无法访问按钮
【发布时间】:2016-03-07 04:01:55
【问题描述】:

我正在尝试单击页面中的一个按钮,当我在 Chrome 浏览器上选择 Inspect 选项时,我可以在该页面中看到其 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>

【问题讨论】:

  • 是动态添加的吗?
  • @guradio 我不确定,但您可能是对的。在这种情况下,有什么我可以尝试的吗?
  • 如果它不在页面源中,则将其添加到脚本中。使用事件委托
  • @charlietfl 你是什么意思event delegation你能提供更多信息吗?
  • 表示它是动态添加的,所以使用event deledation检查此链接api.jquery.com/on

标签: javascript c# html webbrowser-control


【解决方案1】:

我以前也遇到过一个问题,从您的代码示例中不清楚,但是如果您的按钮位于表单的面板内或另一个控件内,则使用 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
        }
    });
    }
};

【讨论】:

  • 非常感谢您的意见。我查看了提供的 MSDN 链接,听起来您可能是对的。我会尝试在我的代码中实现它,并让你知道它是否可以工作。
  • @0014 酷。如果您需要任何帮助,请告诉我。
  • 我检查了Findconrtol 属性,但它似乎用于asp.net 应用程序。我的是一个简单的 Windows 应用程序,我在其中使用 WebBrowser 对象。我试图让它们一起工作,但我失败了。你有什么建议吗?
  • 你可以试试InnerHtml,这里有一个例子:stackoverflow.com/questions/17094136/…显示你的内容的确切布局,我会尽力帮助你,例如,你的按钮所在的控件在,我想看看
  • 感谢您的提议,但我要为您提供页面来源,您需要一个有一定进度的帐户。即使我通过文本文件共享它,也很难在其中找到按钮。这是一个很长的文件:)
【解决方案2】:

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

感谢您的帮助monstertjie_za

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-08
    • 2021-12-08
    • 1970-01-01
    • 2014-07-23
    • 2020-01-22
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多