如何将此foreach循环更改为if语句。它显示每个图像的消息[即使我只点击一个]。我只想在点击图片时显示一条消息......
[代码]
private void webBrowser1_DocumentCompleted(object sender, CompletedEventArgs e)
{
foreach (HtmlElement ele in
webBrowser1.Document.GetElementsByTagName("img"))
{
ele.AttachEventHandler("onclick", Document_Click);
}
}
private void Document_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked an image.");
}
[我试过的]
if (webBrowser1.Document.GetType().GetElementType().Equals("img"))
{
// I tried this
}
HtmlElement elemz;
if (elemz.GetAttribute("type").Equals("img"))
{
// And this
}
HtmlElement elemz;
if (elemz == webBrowser1.Document.GetElementsByTagName("img"))
{
// Also this
}
if (webBrowser1.Document.GetType("img") == true)
{
// Finally I tried this
}
HtmlElement elemz;
if (elemz.GetAttribute("type") == webBrowser1.Document.GetElementsByTagName("img"))
{
// My last hope was this
}
答案 0 :(得分:0)
并不是每个图片都会显示点击事件,因为DocumentCompleted事件多次触发。 (见WebBrowser DocumentCompleted event fired more than once)。如果您检查e.Url以确保您只运行实际页面DocumentCompleted的代码,您将看到该事件仅触发一次。
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
if (e.Url.Equals(webBrowser1.Url)) {
foreach (HtmlElement ele in webBrowser1.Document.GetElementsByTagName("img")) {
ele.AttachEventHandler("onclick", Document_Click);
}
}
}