0

I am inserting link elements and would like to share the clicks, but I'm not getting .. The test code:

<html>
<title></title>
<head>

    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function(){
            $("#teste").click(function(){
               $("body").append($("<a>").text("Element A"));
            });

            $("a").click(function(){
               alert("oi");
            });
        });

    </script>

</head>
<body>
    <input type="button" value="INSERT A" id="teste" />
</body>
</html>

2 Answers2

1

The link is not on the page when you attach the event. It is like trying to eat a pizza before you make it. You either need to attach the event when you click on it or you need to use event delegation.

$(document).on("click", "a", function(){
    alert("oi");
});
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You're trying to register a handler before the element is created, you have to use delegation, that is, register the event on an ancestor node that is already there, and filter it.

jQuery has an easy way to do it.

$(document).on('click', 'a', function(){
   alert("oi");
});
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217