简体   繁体   中英

C# javascript click button by tag and attribute

I'm having some trouble getting my program to click a button:

 <a class="button_recruit" style="letter-spacing: -1px" href="/myrecruitlink" data-executing="0">Recruit</a>      

That is the button I'm trying to click but when I add the code for it it does nothing, I'm new to C# and trying to learn this. So if someone could point out what I'm doing wrong here I would very much appreciate it.

Here is the program code:

 namespace clean_test
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        web.ScriptErrorsSuppressed = true;
        Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current", "", "NULL");
        web.Navigate("http://www.mywebsite.com");
    }

    private void recruit_Click(object sender, EventArgs e)
    {
        HtmlElementCollection elems = web.Document.GetElementsByTagName("a");
        foreach (HtmlElement elem in elems)
        {
            String value = elem.GetAttribute("value");
            if (value != null && value.Length != 0 && value.Equals("Recruit"))
            {
                recruit.PerformClick();
            }
        }
    }


  }
}    

Why don't you go client side ?

<script type="text/javascript">
function NewFunction(){
//do something here
}
</script>

and change to button with OnClientClick attribute

<asp:Button ID="Button1" runat="server" Text="Button" CssClass="button_recruit" style="letter-spacing: -1px"  OnClientClick="recruit_Click"  />

Or add onclick to the existing element you have to fire javascript method.

 <a class="button_recruit" style="letter-spacing: -1px" href="/myrecruitlink" data-executing="0" onclick=""NewFunction();">Recruit</a>   

I think other guys don't understand your question. You need this line:

private void recruit_Click(object sender, EventArgs e)
{
     HtmlElementCollection elems = web.Document.GetElementsByTagName("a");
     foreach (HtmlElement elem in elems)
     {
         String value = elem.GetAttribute("value");

         //you can use elem.InnerText.Equals("Recruit") too, if value == null.
         if (value != null && value.Length != 0 && value.Equals("Recruit"))
         {
             elem.InvokeMember("click");
         }
     }
 }

Hope I help you !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM