1

动态创建具有特定类的元素时是否可以引发 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();
});

谢谢。

4

2 回答 2

2

您可能正在寻找的词是observables。本质上,当 DOM(或者在这种情况下是 span 元素)更新时,您希望触发一个事件。

对于那个答案,我想把你的注意力引向这个回应,

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

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

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

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

 });

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

于 2013-08-10T00:39:09.140 回答
1

当 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');

  });

}
于 2013-08-10T00:46:02.787 回答