jQuery, issue with .each() -
i want reduce every sentence has more 3 letters, code showing first 3 letters, adds "...", clicking on these "..." want show whole sentence. when i'm clicking on every single "..." reveals every sentence instead of sentence clicked on.
my code is:
$('.test').each(function(){ var el = $(this); var textori = el.html(); if(textori.length > 3){ el.html(textori.substring(0,3)+'<span class="more">...</span>'); } $(document).on('click', el.find('.more'), function() { el.html(textori); }); });
here jsfiddle: http://jsfiddle.net/malamine_kebe/gxdsj/
the syntax you've got click handler isn't correct, because it's inside each
loop, because you're not limiting text swapping element clicked. try this:
$('.test').each(function(){ var $el = $(this); var originaltext = $el.html(); if (originaltext.length > 3) { $el.html(originaltext.substring(0,3) + '<span class="more">...</span>'); } $el.data('original-text', originaltext); }); $(document).on('click', '.more', function() { var $test = $(this).closest('.test') $test.html($test.data('original-text')); });
Comments
Post a Comment