-2

我有以下代码,Chrome Inspector 调试时出现错误“Uncaught TypeError: Cannot read property 'substring' of undefined”:

<script type="text/javascript">
  $(function countComments() {
    var mcount = '//api.moot.it/postcounts?path=/forum/comments:' + $(this).closest('article').attr('id').substring(8);
    $.getJSON(mcount, function(json) {
      var results = $('.entry-actions');
      $.each(json, function(key, val) {
        results.prepend('<a class="entry-comments" href="{permalink}#comments" title="Comments">' + val['size'] + ' Comments</a>');
      });
    });
  });
</script>

我很确定问题出在(this),但我在不同的脚本中正确使用了它,.click并且该代码工作得很好。

是因为(this)不能用.ready吗?如果是这样,我怎样才能让这个函数与替代代码一起工作?

用 HTML 编辑:

<article id="article-5344bff8e4b01730378236ff">
  <header class="entry-header cf">
    <p class="entry-actions"></p>
  </header>
    <div class="entry-title-wrapper">

    BLOG CONTENTS

    <div class="entry-injection">
    <script type="text/javascript">
      $(function countComments() {
        var mcount = '//api.moot.it/postcounts?path=/forum/comments:' + $(this).closest('article').attr('id').substring(8);
        $.getJSON(mcount, function(json) {
          var results = $('.entry-actions');
          $.each(json, function(key, val) {
            results.prepend('<a class="entry-comments" href="{permalink}#comments" title="Comments">' + val['size'] + ' Comments</a>');
          });
        });
      });
    </script>
    </div>
    </div>
  </article>
4

1 回答 1

1

The problem is that in document ready function this points to document http://jsfiddle.net/IrvinDominin/J2r5V/

In this case you can't have any article parent element of document, so your function raise the error http://jsfiddle.net/IrvinDominin/J2r5V/1/.

I think you have to get all your div elements according on your needs, and for each of them execute the current function; in the context of the each this will be the correct element.

于 2014-04-14T08:11:51.393 回答