javascript - Why does this dynamically created element not bound to an event? -
<div class="text">(some text...)</div> var text = $(".text").text(); var excerpt = ''; if(text.length > 100) { console.log(text.length); excerpt = text.substr(0, 100); $(".text").html(excerpt + "<div class='readmore'><a href='#'>read more</a</div>"); } $(".readmore").on('click', function() { $(".text").html(text + "<div class='showless'><a href='#'>show less</a></div>"); }); $(".showless").on('click', function() { $(".text").html(excerpt + "<div class='readmore'><a href='#'>read more</a></div>"); });
i trying make excerpt of text using javascript. when "read more" clicked, , whole text , "show less" displayed. , when "show less" clicked, excerpt , "read more" shows again. "show less" not trigger event, "read more" seems work. why?
try this:
$(document).on('click', ".showless", function () { $(".text").html(excerpt + "<div class='readmore'><a href='#'>read more</a></div>"); });
demo: http://jsfiddle.net/fe3hnh4x/1/
and here explanation: event binding on dynamically created elements?
Comments
Post a Comment