【问题标题】:Perform actions on dynamic created div using the ID [closed]使用 ID 对动态创建的 div 执行操作 [关闭]
【发布时间】:2013-12-23 12:20:26
【问题描述】:

当我知道使用此代码动态创建的 div 的 ID 时,如何执行操作(例如更改文本):

Stringbuilder sb = new Strinbuilder();
sb.AppendLine("<div id='example'>I want to change this text</div>");

//Examples using a literal, placeholder or a lable:

litExample.Text = sb.ToString();

phExample.Text = sb.ToString();

lblExample.Text = sb.ToString();



//Call id example and change "I want to change this text" , to something else.
//How do I do this?

提前致谢。

【问题讨论】:

  • 基本上 - 你不会那样做。您可以创建一个 HTMLGenreric 控件并将其添加到您的页面中,这可能会执行您想要执行的操作:msdn.microsoft.com/en-us/library/…。但是您并没有真正提供足够的信息来提供更多建议/帮助。

标签: c# asp.net html dynamic stringbuilder


【解决方案1】:

首先确保您已添加以下命名空间:

using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Text;

并将以下方法添加到您的代码中:

  public string RenderControl(Control ctrl)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter tw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(tw);

        ctrl.RenderControl(hw);
        return sb.ToString();
    }

并将您的代码更改为以下内容:

        //StringBuilder sb = new StringBuilder();
        HtmlGenericControl myDiv = new HtmlGenericControl("div");
        myDiv.InnerText = "I want to change this text";

        //Make sure asp.net does not add any prefix to your Id "example"
        myDiv.ClientIDMode = System.Web.UI.ClientIDMode.Static;
        myDiv.ID = "example";

        //Examples using a literal, placeholder or a lable:

        litExample.Text = RenderControl(myDiv);

        phExample.Text = RenderControl(myDiv);

        lblExample.Text = RenderControl(myDiv);

        //Do Stuff with myDiv as typical control

【讨论】:

    【解决方案2】:

    当页面已经呈现时,您可能希望使用 javascript 来执行此操作。比如:

    document.getElementById('example').innerHTML = 'New text';
    

    如果页面尚未呈现,您可能需要直接在您的字符串构建器中调整字符串,或者在您使用它的每个实例中调整字符串,或者完全使用不同的方法,但是您没有提供足够的信息你的问题是说什么有用的。

    【讨论】:

      【解决方案3】:

      只是一件小事,因为你所有的 DIV 共享相同的 ID,你会在 JS 上度过一段糟糕的时光......

      您可以通过手动设置 ID 并在 Static 上设置 ClientIDMode 来解决问题,以防止 Seyed 指出的自动创建。

      您可以使用自定义 CSS 类一次选择所有项目。

      【讨论】:

      • +1 为您的笔记。是的,你说的没错。但是他的源代码有这个问题。如何生成 id 由他决定。
      • 没错,我在发布最初的答案后看到了生成部分。谢谢^^
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2012-04-14
      • 2011-12-17
      • 1970-01-01
      相关资源
      最近更新 更多