0

Kindly help me. i have created a run time spell check system. The problem i am facing is, when the system returns the correct spelling, it shows the word hyper linked. If the user clicks that hyper link, it should overwrite the word with the suggested work. Unfortunately the jQuery created hyper link is not triggering i have created this dummy project, because actual code is very lengthy. JSfiddle link is this: http://jsfiddle.net/pk2mk863/1/

<html>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<body>

<a href="#" id="testing">Testing</a>
<div id="testing1"></div>

<script>
    $(document).ready(function() {
        $('#testing').click(function () {
            $('#testing1').html('<a href="#" id="testing22">click me again</a>');
        });

        $('#testing22').click(function() {
            alert("i rock");
        });
    }); 
</script>
</body>
</html>
Hadi Khan
  • 3
  • 2

2 Answers2

0

Because you are appending HTML dynamically inside DOM, So use event delegation as shown below :

$(document).on('click','#testing22',function(){
   alert("i rock");
});

Now your complete jquery code will look like as shown below:

<script>
    $(document).ready(function() {
        $('#testing').click(function () {
            $('#testing1').html('<a href="#" id="testing22">click me again</a>');
        });

        $(document).on('click', '#testing22', function() {
            alert("i rock");
        });
    }); 
</script>
Kartikeya Khosla
  • 18,039
  • 8
  • 39
  • 64
0

Use a delegated event handler instead:

e.g.

<script>
    $(document).ready(function() {
        $('#testing').click(function () {
            $('#testing1').html('<a href="#" id="testing22">click me again</a>');
        });

        $(document).on('click', '#testing22', function() {
            alert("i rock");
        });
    }); 
</script>

This works by listening for an event (in this case click) bubbling up to a non-changing ancestor ( in this case document if nothing else is handy). It then applies a jQuery selector and then applies the function to any matching elements that caused the event.

This technique allows you to connect events to elements that do not yet exist.

Gone Coding
  • 88,305
  • 23
  • 172
  • 188