繁体   English   中英

当动态创建具有某个类的元素时,如何引发jquery事件

[英]How to raise a jquery event when an element with some class is created dynamically

当动态创建具有特定类的元素时,是否可以引发jquery事件? 这就是我的意思。 我有以下几点;

...
<div id="lotoContent"></div>
...

使用jquery ajax,我从服务器检索几行并将它们附加到“lotoContent”div。 每行都有一个空的span元素,如下所示

<span class="lotoDateTime" data-date="123456"></span>

data-date属性的值是从数据库中恢复的unix时间戳。 添加行后,将调用以下javascript函数;

function processDateTimes() {
   //process dates
    $('.lotoDateTime').each(function () {
        var timeStamp = $(this).data('date');
        $(this).text(getDateTimeFromServerUnixTimeStamp(timeStamp));
    });

}

function getDateTimeFromServerUnixTimeStamp(timeStamp) {
  //this function takes the unix time-stamp and converts it to Date and Time 
  // like 08/09/2013 12:09 based on the browser time
}

这工作正常,但我想知道是否有一种方法可以在创建日期跨度时自动调用processDateTimes(),而不是在创建日期后手动调用该函数。 这样的事情就是我想到的;

$('#lotoContent').on('SomeEvent', '.lotoDateTime', function() {
  processDateTimes();
});

谢谢。

你可能正在寻找的词是可观察的 实质上,当DOM(或在这种情况下是span元素)更新时,您想要触发事件。

对于那个答案,我想引导你注意这个回答,

https://stackoverflow.com/a/240663/191006

Ken表明,捕获顶部的所有DOM更改将允许您选择对某些内部元素执行的操作。

$('body').change(function(event){

    if( $(event.target).hasClass("lotoDateTime") )
        processDateTimes();

 });

你当然可以清理它......你不需要像我一样检查课程......但我希望这能帮助你朝着正确的方向前进。

当ajax填充它们并更改函数processDateTimes()以在类“new”的项目上运行时,你能否给新行一个“new”类,然后在它完成它之后删除它。

最后在你的ajax调用结束时调用函数(完成)?

$.ajax( ... ,
  success: function() {
    // add your element and give it a class of "new"
  },
  complete: function() {
    // then run your process function:
    processDateTimes();
  }
);

// this will only run on "new" items added
function processDateTimes() {

  $('.lotoDateTime.new').each(function() {
    var timeStamp = $(this).data('date');
    $(this)
      .text(getDateTimeFromServerUnixTimeStamp(timeStamp))
      .removeClass('new');

  });

}

暂无
暂无

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

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