jquery - Javascript function calling itself -
i have javascript function 2 parameters : results object array , i index.
the function displays item array. want to build links show other entries in array.
my code is:
function rendernews(results, i) { $('.articletitle').text(results[i].title); $('.articlebody').text(results[i].newsbody); // build links var linkhtml = ''; (var = 0; < results.length; i++) { linkhtml += '<a href="#" onclick="rendernews(results, ' + + ')">' + (i + 1) + '</a> '; } $('.articleactions').html(linkhtml); }
as can see setting onclick function call redraw results. "function not defined error".
i'm still learning go. bad idea function call itself? wonder if can advise on right way of doing this.
if understand, rendernews
called when page gets loaded, right? actually, links put inside component articleactions
class. idea, clicking link call function again, , links replaced new links. sounds strange. also, can't tell expect when passing results
onclick event. actually, if idea reuse same results array, passing undefinitely same function on , on again, make things simpler:
function rendernews(results) { if (results.length == 0) return; // build links var linkhtml = ''; (var = 0; < results.length; i++) linkhtml += '<a href="#" data-articletitle="' + results[i].title + '" data-articlebody="' + results[i].newsbody +'" class="article-link">' + (i + 1) + '</a> '; $('.articleactions').html(linkhtml); $('.articletitle').text(results[0].title); $('.articlebody').text(results[0].newsbody); } $('.article-link').click(function(){ $('.articletitle').text($(this).data('articletitle')); $('.articlebody').text($(this).data('articlebody')); });
as far understand, whenever want update current articles, call rendernews
build/rebuild lot of links each article in array holding data (title , body), , load first item. rendernews
going called once page loads (i don't know how intend this).
there click event component article-link class, in case links (anchors). when 1 clicked, updates screen (article's title , body) data.
you improve code keep track of selected item, , once rendernews
called, load article instead of first one. or keep passing article's index parameter, example.
since don't know how call rendernews
function, it's hard make better code, might clear you.
simple jsfiddle demo
Comments
Post a Comment