当动态创建具有特定类的元素时,是否可以引发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();
});
感谢。
答案 0 :(得分:2)
您可能正在寻找的词是 observables 。实质上,当DOM(或在这种情况下是span元素)更新时,您想要触发事件。
对于这个答案,我想引导你注意这个回应,
https://stackoverflow.com/a/240663/191006
Ken表示,捕获顶部的所有DOM更改将允许您选择对某些内部元素执行的操作。
$('body').change(function(event){
if( $(event.target).hasClass("lotoDateTime") )
processDateTimes();
});
你当然可以清理它......你不需要像我一样检查课程......但我希望这能帮助你朝着正确的方向前进。
答案 1 :(得分:1)
当ajax填充它们时,你能否给新行一个“new”类 更改函数 processDateTimes()以在类别为“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');
});
}