2014-07-15 59 views
0

需要從沒有ID或名稱的div標籤的子元素調用onclick方法。在我的網站上有很多div標籤。我想遍歷具有類名稱的特定div標籤,並獲取其子元素標籤,該標籤也具有id並調用其中包含的onclick方法。 HTML:如何調用div標籤中的onclick事件子元素

新事件

我使用的web瀏覽器控件在C#中,但不能能夠訪問一個標籤,並調用該方法,因爲很多div標籤都在那裏。 PS沒有htmlagilitypack。它是一個安全的環境,我無法下載這些包。

回答

0

如果您不想使用HtmlAgilityPack,則可以使用C#XPath API。它的功能相同。除了正則表達式,這可能是最簡單的方法。

0

如果子元素「確實有ID」,那麼這個ID應該是HTML文檔中是唯一的,然後通過C#代碼子元素「點擊」可以實現爲以下幾點:

 var doc = webBrowser1.Document; 
     string childTagId = "{{type your child tag id here}}"; 

     doc.GetElementById(childTagId).InvokeMember("click"); 

但如果孩子標籤的ID在HTML文檔中不是唯一的,並且DIV的類名是唯一的(根據您的描述進行假設),那麼C#代碼將變爲:

 var doc = webBrowser1.Document; 
     string childTagId = "{{type your child tag id here}}"; 
     string className = "{{type your test className here}}"; 
     string childTagName = "{{type your child tag name here}}"; 

     doc.GetElementsByTagName("div").OfType<System.Windows.Forms.HtmlElement>() 
       .Where(x => x.GetAttribute("className") == className).First() 
       .All.OfType<System.Windows.Forms.HtmlElement>() 
       .Where(x => string.Compare(x.TagName, childTagName, true) == 0 && 
          x.GetAttribute("id") == childTagId) 
       .First() 
       .InvokeMember("click"); 
相關問題