2011-03-13 68 views
0

我有以下内嵌JavaScript,即时通讯使用jquery倒计时插件来显示剩余时间。避免重复使用jquery每个项目的相同代码

此代码与页面上的每个“注释”一起存在,因此它在页面上重复多次。我怎样才能让这个外部?并避免重复?

即时通讯使用.nt mvc剃须刀和附加ID。

<script type="text/javascript"> 
    $(function() { 
    var dateLeft = new Date(@(item.UnixTicks)); 
    $('#[email protected](item.ID)').countdown({until: dateLeft, format:'MS', onExpiry: liftOff, onTick: watchCountdown}); 

    function liftOff() { 
     alert('We have lift off!'); 
    } 

    function watchCountdown(periods) { 
     $('#[email protected](item.ID)').text('Just ' + periods[5] + ' minutes and ' + 
      periods[6] + ' seconds to go'); 
    } 
    }); 
</script> 

回答

2

你可以把UnixTicks为属性的评论,给所有的注释class="comment",并遍历它们:

$('.Comment').each(function() { 
    var dateLeft = new Date(parseInt($(this).attr('data-unixticks'), 10)); 
    ... 
}); 
+2

而同样用'item.ID'属性.. :) – 2011-03-13 14:32:09

+1

@Shadow:或者调用'.find' – SLaks 2011-03-13 14:33:29

+1

如果'#monitor-'元素嵌套在“main”'div'里面,那么给它们类会更好* monitor *然后简单的'$(this).find(“。monitor”)'会找到它。太好了! – 2011-03-13 14:37:50