星期一, 10月 01, 2007

WebBrowser處理網頁元件attribute, style及event

1.設定或取得html tag的屬性值
ex.

//set htmlDoc
HtmlDocument htmlDoc = webBrowser1.Document;

//set Element where tag's name is "Name"
HtmlElement tbUserid = htmlDoc.All["Name"];
HtmlElement tbPasswd = htmlDoc.All["Nickname"];

//set the content of tag's attribute "value"
tbUserid.SetAttribute("value", "Kevin");
tbPasswd.SetAttribute("value", "ok1234");

//get the content
String name = tbUserid.GetAttribute("value");

p.s 某些tag無法用name取得,只能用id來取得

2.設定或取得html tag的文字
hello
同上取得HtmlElement後
HtmlElement tmp = htmlDoc.All["wellcomeTag"];
tmp.SetInnerHtml("you got it") //set
tmp.GetInnerHtml() //get

p.s document如果為XML的話,得用InnerText (好像吧 哈)

3.改變Style
同上取得HtmlElement後
tmp.Style = "display: none";

4.增加onclick事性

HtmlElement imgElement1 = htmlDoc.All["PlayBall"];
if (imgElement1 != null)
{
imgElement1.AttachEventHandler("onclick", new EventHandler(imgElement1_Click));
}

//click event
private void imgElement1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("let's have some fun");
}

沒有留言: