Javascript:如何在每个()上使用on()方法?

时间:2016-08-02 03:31:46

标签: javascript jquery html ajax

我已经学会了on() ables来绑定新注入的元素:

$(document).on( eventName, selector, function(){} );

我希望我的自定义timecountdown函数适用于加载页面时的所有$('。timecountdown'),这也适用于新检索的帐户。我的代码如下所示:

<html>
<div class="timecountdown">50seconds</div>
<div class="timecountdown">20seconds</div>
<div class="timecountdown">60seconds</div>
...
...
...
</html>
<script>
$(function(){
$('.timecountdown').each(function(){
   //code to counting down time on each elements using by javascript setInterval() 
     function, which minus one to the residual integer for every seconds.
   //code to delete old account when time hits zero, then retrieve new accounts 
     via ajax post method     
     $.post("accountupdate.php", {id:id}, function(result){
       code to display new <div class="timecountdown">Xseconds</div> account
     })

})
</scirpt>

我试过了:

 $(document).on(each, $('.timecountdown'), function(){
 code to countdown time, delete and retrieve
 } );

2 个答案:

答案 0 :(得分:0)

each不是事件方法,而是迭代DOM元素。 on方法仅用于事件处理,因此您在使用each方法时无需担心事件委派方法。

答案 1 :(得分:0)

jQuery each()方法是一个通用迭代器函数,可用于无缝迭代对象和数组,而on()方法将一个或多个事件的事件处理函数附加到所选元素。

可能你可以这样试试

$("body").on({
    mouseover: function() {
            $('.timecountdown').each(function(){
               $.post("accountupdate.php", {id:id}, function(result){
                   code to display new <div class="timecountdown">Xseconds</div> account
                });
            });
    }
});