简体   繁体   English

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

[英]Binding client side event to dyanamic datalist items using jquery

I got stuck in a problem. 我陷入了一个问题。 I am loading elements in a datalist dynamically. 我正在动态加载数据列表中的元素。 and i am trying to bind click event on a column using jquery. 而且我正在尝试使用jquery在列上绑定click事件。 It works fine when i use master page with it. 当我与它一起使用母版页时,它工作正常。 as it follows the page life cycle and loading jquery after child page data binding. 因为它遵循页面生命周期,并在子页面数据绑定之后加载jquery。 But when i use it in a normal page(without master page) it does not allow me to perform desired action. 但是,当我在普通页面(没有母版页面)中使用它时,它不允许我执行所需的操作。 I know why is this happening, the reason is jquery is being loaded before elements binding. 我知道为什么会这样,原因是在元素绑定之前加载了jquery。 so jquery is not able to bind click event since it is not able to find those controls. 因此,jQuery无法绑定click事件,因为它无法找到那些控件。

binding elements already have "item" class in them 绑定元素中已经具有“ item”类

here is my jquery code: 这是我的jQuery代码:

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

code behind: 后面的代码:

 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') make it more specific based on your html $('body')根据您的html使其更加具体

I also had the same problem once and this problem really is a pain. 我曾经也遇到过同样的问题,这个问题确实很痛苦。

Here is my solution: 这是我的解决方案:

Instead of binding with click create a function for example: 不用单击绑定,例如,创建一个函数:

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

and call this function after data binding is done. 并在数据绑定完成后调用此函数。 it will be good if you are using update panel. 如果您使用的是更新面板,那就太好了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM