使用 jquery 将客户端事件绑定到动态数据列表项

Binding client side event to dyanamic datalist items using jquery

本文关键字:动态 数据 列表 绑定 jquery 客户端 事件 使用      更新时间:2023-09-26

我陷入了一个问题。我正在动态加载数据列表中的元素。我正在尝试使用 jQuery 在列上绑定单击事件。当我使用母版页时,它工作正常。因为它遵循页面生命周期并在子页面数据绑定后加载 jQuery。但是当我在普通页面(没有母版页)中使用它时,它不允许我执行所需的操作。我知道为什么会这样,原因是在元素绑定之前加载了jquery。因此,jQuery无法绑定点击事件,因为它无法找到这些控件。

绑定元素中已包含"item"类

这是我的jquery代码:

$(document).ready(function () {
    $('.item').click(function () {
          //do something here
   });
});

代码隐藏:

 protected void Page_Load(object sender, EventArgs e)
 {
     using (TestEntites db = new TestEntites())
    {
        IEnumerable<Template> Test = from t in db.Template
                                                    where t.Customer == clsuser.CustomerID
                                                        && t.Region == user.RegionID
                                                    select t;
        dlTemplateGroups.DataSource = Test;
        dlTemplateGroups.DataBind();
        BindTemplates(db);
    }     
 }
$(document).ready(function () {
    $('body').on('click', '.item' ,function () {
          //do something here
   });
});

$('body') 根据您的 html 使其更具体

我也曾经遇到过同样的问题,这个问题真的很痛苦。

这是我的解决方案:

而不是使用单击绑定,例如创建一个函数:

function reBinding()
{
      $('.item').on("click",function () {
      //do something here
      });
}

并在数据绑定完成后调用此函数。 如果您使用的是更新面板,那就太好了。

ScriptManager.RegisterStartupScript(rptGridAlbum.GetType, "scriptname", "reBinding();", True)