我可以通过div onclick事件调用函数后面的代码吗?

时间:2012-05-15 08:33:31

标签: asp.net vb.net

我的页面上有一堆div,它们是在运行时动态添加的。 当点击任何动态添加的div时 - 所有需要在后面的代码中调用相同的函数。每个div必须将自己的ID传递给函数。 我无法使用Web方法,因为函数需要识别单击哪个div,然后显示/隐藏/填充页面上的其他控件。

干杯球员

            标题控件和东西都在这里          
    <div id="div_Footer" class="HoverEdit" title="Click To Edit" runat="server" onclick="EditDiv(div_Footer)">
        Footer Controls and stuff go here
    </div>

然后在后面的代码中:

Sub EditDiv(ID_ofDiv As String)

    'Do some stuff to the controls on the page
    'Swapping tabs, showing /hiding controls etc.

End Sub

3 个答案:

答案 0 :(得分:3)

我不习惯编写VB代码,所以我的例子是在C#中,但也许它可以帮助你开始。 它可能不是实现这一目标最干净的方式,但我会试一试:

<强> HTML

 <div id="div_Footer" class="HoverEdit" title="Click To Edit" runat="server" onclick="EditDiv(this)">
        Footer Controls and stuff go here
    </div>

<强>客户端

<script type="text/javascript">
function EditDiv(s,e){
var id = $(s).attr("id");
__doPostBack(id,id);
}
</script>

服务器

private void Page_Load(object sender, EventArgs e)
{
   var arg = Request.Form["__EVENTTARGET"]; 'this will be empty on your first page request, but if the user click a div it will cause a postback to server, so this event will be fired again and will contain the div ID.

   if(arg != null)
   {
      string divID = (string)arg;
      'call your method with the argument.
   }
}

有关这方面的更多信息,请访问:

http://wiki.asp.net/page.aspx/1082/dopostback-function/

答案 1 :(得分:0)

在@Tim Schmelter发布的link的帮助下,我尝试了以下内容。这太棒了:

标记:

<div id="div1" runat="server" style="height:100px;width:100px;">click me</div>

代码:

public class MyPage  
      Inherits System.Web.UI.Page
      Implements IPostBackEventHandler

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    div1.Attributes("onclick") = 
         Me.Page.ClientScript.GetPostBackEventReference(Me, "div1_clicki")
End Sub

Protected Sub Div1_Click()
    'do your stuff
    div1.InnerHtml="div1 clicked"
End Sub


'Private Members As IPostBackEventHandler
Public Sub RaisePostBackEvent1(ByVal eventArgument As String) Implements 
                    IPostBackEventHandler.RaisePostBackEvent
    If eventArgument = "div1_click" Then
            div1_click()
        End If
    End If
End Sub

答案 2 :(得分:0)

您可以从javascript创建回发。一种方法是创建一个按钮或链接按钮并向其添加单击事件。添加 Style =“显示:无;”并强制Div按下按钮点击后回传。

<div id="div_Footer" class="HoverEdit" title="Click To Edit" runat="server" onclick="EditDiv(this)">
    Footer Controls and stuff go here
</div>
//Javascript
function EditDiv()
{
   // do your code
   __doPostBack('ButtonAID','')
}

可以在下面的文章中找到一个很好的解释。 ASP.NET postback with JavaScript