preventDefault not working on anchor

2020-07-10 06:40发布

问题:

I'm trying to log the click on an anchor that's being generated asynchronously.

The asynchronous call - which works perfectly fine - looks like this:

 $("#txt_search").keyup(function() {
    var search = $("#txt_search").val();

    if (search.length > 0)
    {
      $.ajax({
        type: "post",
        url: "<?php echo site_url ('members/searchmember') ;?>",
        data:'search=' + search,
      success: function(msg){
        $('#search_results').html("");
        var obj = JSON.parse(msg);

        if (obj.length > 0)
        {
          try
          {
            var items=[];   
            $.each(obj, function(i,val){                      
                items.push($('<li class="search_result" />').html(
                  '<img src="<?php echo base_url(); ?>' + val.userImage + ' " /><a class="user_name" href="" rel="' + val.userId + '">'
                  + val.userFirstName + ' ' + val.userLastName 
                  + ' (' + val.userEmail + ')</a>'
                  )
                );
            }); 
            $('#search_results').append.apply($('#search_results'), items);
          } 
          catch(e) 
          {   
            alert(e);
          }   
        }
        else
        {
          $('#search_results').html($('<li/>').text('This user does not have an account yet'));   
        }   

      },
      error: function(){            
        alert('The connection is lost');
      }
      });
    }
  });

The anchor I want to get to is <a class="user_name" href="" rel="' + val.userId + '">' + val.userFirstName + ' ' + val.userLastName + ' (' + val.userEmail + ')</a>'

I detect the click on these anchors with this function:

  // click op search results
  $("a.user_name").on('click', function(e) {
    e.preventDefault(); 
  });

The problem seems to be that the preventDefault is not doing anything... I've looked at most of the questions involving this problem on Stackoverflow and checked jQuery's own documentation on the topic, but I can't seem to find what's wrong. I've tried adding a async: false statement to the AJAX-call, because perhaps the asynchronous call might be the problem, but that didn't fix it.

回答1:

Event does not bind with dynamically added element unless you delegate it to parent element or document using on(). You have to use different form of on for event delegation.

$(document).on('click', 'a.user_name', function(e) {
    e.preventDefault(); 
});

delegated events

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, Reference



回答2:

The .on() syntax you showed will only bind handlers to elements that match the selector at that moment - not to elements added in the future. Try this instead:

$("#search_results").on("click", "a.user_name", function(e) {
  e.preventDefault(); 
});

This binds a handler to the parent element, and then when a click occurs jQuery only calls your callback function if the actual target element matches the selector in .on()'s second parameter at the time of the click. So it works for dynamically added elements (as long as the parent exists at the time the above runs).



回答3:

This should work for you -

$('.search_result').on('click', 'a.user_name', function(){
    // your code here
    // code
    return false;   
});


回答4:

try this

 $("a.user_name").on('click', function(e) {
    return false;
  });

or

  $(document).on('click', 'a.user_name', function(e) {
      e.preventDefault(); 
          });

Difference between .on() functions calls



回答5:

I had this problem too, and it turned out my selector was wrong.



回答6:

May be your a href linked with other listeners too. Check with event.preventDefault event.stopImmediatePropagation(); together. You can check this site for more info https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/