Javascript – 使用timeago函数和Algolia自动完成功能

我试图使用这些
example中的timeAgo函数.我把它放在一个文件中,我在我的视图中调用它,如下所示:

<script src="{{ asset('js/landing-page/jquery.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('js/landing-page/bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('js/landing-page/material.min.js') }}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.0/js/swiper.min.js"></script>
<script type="text/javascript" src="{{ asset('js/slider.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/timeago.js') }}"></script>

<!-- Include AlgoliaSearch JS Client and autocomplete.js library -->
<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
<script src="https://cdn.jsdelivr.net/autocomplete.js/0/autocomplete.min.js"></script>
<script type="text/javascript" src="{{ asset('js/autocomplete.js') }}"></script>

<!-- Control Center for Material Kit: activating the ripples, parallax effects, scripts from the example pages etc -->
<script src="{{ asset('js/landing-page/material-kit.js') }}" type="text/javascript"></script>

Algolia自动完成模板的部分脚本如下所示:

{
      source: autocomplete.sources.hits(videos, { hitsPerPage: 5 }),
      displayKey: 'title',
      templates: {
        header: '<div class="aa-suggestions-category">Videos</div>',
        suggestion: function(suggestion) {
          return '<span>'
                + '<a href="/player/' + suggestion.id + '">'
                +   '<div class="media">'
                +     '<div class="media-left">'
                +       '<img class="media-object" src="https://s3.eu-central-1.amazonaws.com/myUrl/' + suggestion.video_id + '_1.jpg">'
                +     '</div>'
                +     '<div class="media-body">'
                +       '<p>' + suggestion._highlightResult.title.value + '<small><abbr class="timeago" title="' + suggestion.created_at + '">' + suggestion.created_at + '</abbr></small>' + '</p>'
                +       '<small> ' + '</small>'
                +     '</div>'
                +   '</div>'
                + '</a>'
                +'</span>';
        }

但时间戳仍然是可见的,而不是以前.控制台中未显示任何错误.我究竟做错了什么?

最佳答案 DOM准备就绪后,自动完成会在很长一段时间内添加HTML代码,因此当仍然没有任何自动完成代码时会执行timeago.js代码.

您必须在使用自动完成更新事件呈现新代码后立即再次调用timeAgo函数,而不是等待60或10秒.

//attach custom event handler - autocomplete:updated triggers when dataset is rendered
autocomplete('#search-input', { hint: false }, [
    {
      source: ...,
      displayKey: ...,
      templates: {
        suggestion: function(suggestion) {
          ...
        }
      }
    }
  ]).on('autocomplete:updated', function(event, suggestion, dataset) {
    timeAgo('.timeago');
  });

这个解决方案可以导致timeAgo javascript超时的许多瞬间.用全局timeAgoTimeout = setTimeout(timeAgo,60000)修复它;和timeAgo之前的clearTimeout(timeAgoTimeout).

适用于您可以在小提琴中找到的动态元素的示例 – http://jsfiddle.net/mge45ugr/

点赞