I have a Web Part that dynamically inserts div tags written in VS2010 using C#. I want to implement mouseover events for these div's. When the Web Part 开发者_如何转开发is deployed onto SP2010, my JavaScript is not able to find these div's when I just search for them with the control id that I have specified.
When I checked the page source, I found that some tags like ct100_m_g_
are prefixed to the control id that I have specified.
How can I guess these ids?
The ctlxxx stuff is automatically prepended to the control's ID by ASP.NET, to generate the client ID.
If you want to set a deterministic client ID, you can set the ClientID property instead of the ID property. See http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
In webparts you can use the client ID to find your controls in javascript. Take a look at this example and it will become clear:
using System;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
namespace MyDemo.WebParts
{
public class MyWebPart : WebPart
{
private TextBox txtInput;
private TextBox txtOutput;
private Button btnDoSomething;
protected override void CreateChildControls()
{
base.CreateChildControls();
txtInput = new TextBox();
Controls.Add(txtInput);
txtOutput = new TextBox();
txtOutput.ReadOnly = true;
Controls.Add(txtOutput);
btnDoSomething = new Button();
btnDoSomething.Text = "Do Something";
btnDoSomething.OnClientClick = string.Format("DoSomething('{0}', '{1}'); return false;", txtInput.ClientID, txtOutput.ClientID);
Controls.Add(btnDoSomething);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// Check if the script is already registered, this is necessary because the webpart can be
// added multiple times to the same page
if (!Page.ClientScript.IsClientScriptBlockRegistered("MyWebPartScript"))
{
StringBuilder sb = new StringBuilder();
sb.Append("function DoSomething(inputControlID, outputControlID){");
sb.Append(" var inputControl = document.getElementById(inputControlID);");
sb.Append(" var outputControl = document.getElementById(outputControlID);");
sb.Append(" outputControl.value = inputControl.value;");
sb.Append("}");
Page.ClientScript.RegisterClientScriptBlock(GetType(), "MyWebPartScript", sb.ToString(), true);
}
}
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
EnsureChildControls();
writer.Write("<table>");
writer.Write("<tr><td>");
txtInput.RenderControl(writer);
writer.Write("</td><td>");
txtOutput.RenderControl(writer);
writer.Write("</td></tr><tr><td colspan=\"2\">");
btnDoSomething.RenderControl(writer);
writer.Write("</td></tr></table>");
}
}
}
You could give each of your DIVs a class when generating them. THen, just use the class name to select them and add the event handler.
精彩评论