【问题标题】:How can I add an onclick event to a div that was created in the C# code behind?如何将 onclick 事件添加到在后面的 C# 代码中创建的 div?
【发布时间】:2017-04-03 21:05:23
【问题描述】:

在这里,我在循环中创建了一个 div(该 div 填充了我数据库中的标签/数据):

    HtmlGenericControl availableTime =
    new HtmlGenericControl("div");
    availableTime.Attributes["id"] = "availableTime" + idCount.ToString();
    availableTime.Attributes["runat"] = "server";
    availableTime.Attributes["class"] = "availableTimeDiv";
    availableTime.Attributes.Add("onclick", "divClick()");

这是我要调用的函数:

    protected void divClick(object sender, EventArgs e)
    {
        Response.Redirect("CreateMeeting.aspx");
    }

该函数永远不会被调用,并且 div 不可点击。

另外,我需要获取 div 的 id 和 div 中的其他元素。代码中的方法调用是不是最好的方法?

【问题讨论】:

    标签: javascript c# .net master-pages


    【解决方案1】:

    我可以为您提供一般示例,因为您没有询问任何具体内容,但可以说这可能看起来像这样:

    _myButton.Attributes.Add("onclick", "return confirm_delete();");
    
    javascript:
    function confirm_delete()
    {
      if (confirm("Are you sure you want to delete the custom search by pressing button on div?")==true)
        return true;
      else
        return false;
    }
    

    基本上语法是这样的:

    div.Attributes.Add("onclick", DoSomething);
    

    再举一个例子:

    Button divButton = new Button();
    divButton.Attributes["style"] = "display:none;";
    divButton.ID = "divBtn_" + id;
    divButton.Text = id;
    divButton.Click += divButton_Click;
    

    div.Attributes.Add("onclick", "return divclick();");

    <script>
    function divclick()
    {
        var button = document.getElementById('divBtn_');
        button.click();
    
        return false;
    }
    </script>
    

    我希望这足以让您了解如何在您的 div 上附加点击事件..

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 2010-11-13
      • 2012-01-04
      • 2012-03-18
      • 1970-01-01
      • 2011-07-24
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多