0

In first I excuse with you for my English! I have been studying since 2 years!

I have this problem with my function for loading a messagges quote for my website.

The function could work in this way:

  • Users click on a link like as

    <a class="quote" href="i.quote.php?n=022050" rel="quote_link">Show quote</a>

  • An ajax function get the text quoted.

  • Response text replaces

    <a class="quote" href="i.quote.php?n=022050" rel="quote_link">Show quote</a>

    with

    <blockquote class='rounded'>text quote found</blockquote>

All works fine! Problem is when in the response text, there is another link which shows another quotes.So when I click it, function doesn't work and browser load directly the link quote.

This is the function:

$('a[rel=quote_link]').on('click',function(){

 linkQuote = $(this).attr('href');
 textQuoted = $.ajax({url:linkQuote,type:"GET",async:!1}).responseText;

 $(this).replaceWith( "<blockquote class='rounded'>" + textQuoted + "</blockquote>" );

 event.preventDefault();

});

I have read on stackoverflow.com that to use jQuery .on(), but function still doesn't work!

Thank you at everyone :).

Sorry for my English and I hope that I understand the rules of posting new question.

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80

1 Answers1

1

There are two types of event handling - static event handling and delegated event handling (both are done with .on(). Static event handlers are attached directly to any objects that match your selector and exist at the time you install the event handler. That's what you're using so, since the newly created elements don't exist at the time you install your event handlers, they don't get any event handlers on them.

You can either switch to delegated event handling or you can manually install the event handler on newly created DOM elements.

See these references for how to use delegated event handling:

jQuery .live() vs .on() method for adding a click event after loading dynamic html

jQuery .on does not work but .live does

Does jQuery.on() work for elements that are added after the event handler is created?

The basic concept of delegated event handling is:

$(some static parent selector).on("click", 'a[rel=quote_link]', function() {...});
Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979