我有以下代码,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>