(这)不起作用;结果是“未捕获的类型错误:无法读取未定义的属性“子字符串””
-
23-12-2019 - |
题
我有以下代码,Chrome Inspector 调试时出现错误“Uncaught TypeError:无法读取未定义的属性“子字符串”:
<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>
解决方案
问题是在文档就绪函数中 this
指向文档 http://jsfiddle.net/IrvinDominin/J2r5V/
在这种情况下你不能有任何 article
文档的父元素,因此您的函数会引发错误 http://jsfiddle.net/IrvinDominin/J2r5V/1/.
我想你必须得到你所有的 div
根据您的需要元素,并为每个元素执行当前函数;在每个的背景下 this
将是正确的元素。
不隶属于 StackOverflow