(this) isn't working; results in “Uncaught TypeError: Cannot read property 'substring' of undefined”
-
23-12-2019 - |
Question
I have the following code which Chrome Inspector debugs with the error "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>
I'm pretty sure the problem is with (this)
, but I used it properly in a different script with .click
and that code works just fine.
Is it because (this)
can't be used on .ready
? If so, how could I get this function to work with alternative code?
EDIT with 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>
Solution
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.