0

I have the following LINK in HTML razor:

<a class="btnOpen" data-id="@item.Id">
   Link
</a>

And the next Script

$('.btnOpen').click(function () {
    alert("The Link was clicked");
});

All in INDEX.HTML, it's works fine

I have to change the view using AJAX, and re-create the Link with the following code:

$.ajax({
            type: "post",
            url: "/Controller/Action",
            data: jQuery.param({ cod: cod }),
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            success: function (newId) {
                $('body').append(" <a class='btnOpen' data-id='"+newId+"'>     Link </a> ");
            }
        });

This show the new Link but does not call to .btnOpen Function. I dont know why and which is the scope of the click event when using Ajax

1 Answer 1

3

That's because $('.btnOpen').click runs on whatever is present in the body at the time being called, and your ajax response isn't in the body at that time. Therefore the event handler isn't registered to your new link.

Instead, you should use a delegated event handler from jQuery to make it dynamically listen to your DOM:

$('body').on('click', 'a.btnOpen', function () {
    alert("The Link was clicked");
});

function add() {
  $('#content').append('<a href="#" class="btnOpen">Click me dynamically</a>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="content">
   <a href="#" class="btnOpen">Click me</a>
</div>

<button onclick="add()">Add link</button>

You want to have the event bound to something you know exists, and is as close as possible to your dynamically added content. So for instance, if all of them resides in a div, use the div to create the .on handler.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.