如何将onclick事件添加到在C#代码后面创建的div?

时间:2017-04-03 21:05:24

标签: javascript c# .net master-pages

这里我在循环中创建了一个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中获取div和其他元素的id。在代码中调用方法是最好的方法吗?

1 个答案:

答案 0 :(得分:1)

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

import tkinter
import tkinter.filedialog
def center_window(width, height):
    # get screen width and height
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    # calculate position x and y coordinates
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.geometry('%dx%d+%d+%d' % (width, height, x, y))

def OnButtonClick(self):
    self.entryVariable.set( tkinter.filedialog.askopenfilename() )
    self.entry.focus_set()
    self.entry.selection_range(0, tkinter.END)


root = tkinter.Tk()
center_window(400, 300)
root.title("A simple GUI")
root.entryVariable = tkinter.StringVar()
frame=tkinter.Frame(root)
root.entry = tkinter.Entry(frame,textvariable=root.entryVariable)
B = tkinter.Button(frame, text ="Choose", command=lambda: OnButtonClick(root))
root.entry.grid(column=0,row=0)
B.grid(column=1,row=0)
frame.pack(pady=100)  #Change this number to move the frame up or down
root.mainloop()

Bassically语法如下:

_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);

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

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

我希望您能够了解如何在您的div上附加Click事件。