简体   繁体   中英

jQuery preventDefault() not working with .on()

Yes, I have read through many other posts with the same problem, but I'm not understanding how to fix this. I created a bookmarking button, and it needs to change icons on click.

My jQuery:

jQuery(document).ready( function() {
    
    var bm = jQuery(".user_bookmark");
    
    bm.on("click", ".user_bookmark", function (e) {
        e.preventDefault(); 
        post_id = jQuery(this).attr("data-post_id")
        nonce = jQuery(this).attr("data-nonce")

        jQuery.ajax({
         type : "post",
         dataType : "json",
         url : bookmarkAjax.ajaxurl,
         data : {action: "eri_user_bookmark", post_id : post_id, nonce: nonce},
         success: function(response) {
            if(response.type == "success") {
                var add = 'Add Bookmark';
                var remove = 'Remove Bookmark';
                var display = bm.attr('display');
                var bookmarked = bm.attr('bookmarked');
                if (display == 'icon') {
                    add = '<i class="x-icon" data-x-icon-o="&#xf02e;" aria-hidden="true"></i>';
                    remove = '<i class="x-icon" data-x-icon-s="&#xf02e;" aria-hidden="true"></i>';
                }
                if (bookmarked) {
                    bm.html(remove);
                    bm.attr('bookmarked', 'false');
                } else {
                    bm.html(add);
                    bm.attr('bookmarked', 'true');
                }
            }
            else {
               alert("Your bookmark could not be added")
            }
         }
        })  
    });

})

First I had bm.click() , but it was only working with one click, then I read to switch to the .on() function, and now it's refreshing the page.

I tried switching out function (e) with function () and replacing e.preventDefault(); with return false; , e.stopImmediatePropagation(); , and e.stopPropagation(); .

Also tried switching bm.on() with jQuery(document).on() with all of these variations. That still ran my code and did not refresh, but it's not changing the elements from the jQuery code.

Example HTML:

<a class="user_bookmark" data-nonce="2b92b05de9" data-post_id="1" href="https://example.com/wp-admin/admin-ajax.php?action=eri_user_bookmark&amp;post_id=1&amp;nonce=2b92b05de9" display="icon" bookmarked="true" style="outline: none;">
   <i class="x-icon" data-x-icon-s="" aria-hidden="true"></i>
</a>

Full PHP Gist: https://gist.github.com/mrgandy/91361fca86e769235eec684a4647b875

The issue is because you're accidentally nesting the event handler. You're attaching a delegated event handler to .user_bookmark which is listening for click events on child .user_bookmark elements. Your HTML shows these elements are not nested, hence the event handler never fires so neither preventDefault() , or your AJAX request, is called.

Assuming the <a /> elements you're trying to target are not dynamically created, then remove the second argument you're using in the on() call.

 jQuery($ => { var $bm = $('.user_bookmark'); $bm.on('click', function(e) { e.preventDefault(); let post_id = $(this).data('post_id'); let nonce = $(this).data('nonce'); console.log(post_id, nonce); console.log('ajax request here...'); }); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class="user_bookmark" data-nonce="2b92b05de9" data-post_id="1" href="https://example.com/wp-admin/admin-ajax.php?action=eri_user_bookmark&amp;post_id=1&amp;nonce=2b92b05de9" display="icon" bookmarked="true" style="outline: none;"> <i class="x-icon" data-x-icon-s="" aria-hidden="true"></i> Lorem ipsum </a>

If the elements are in fact dynamically added to the DOM after the page loads, then you need to assign the delegated event handler to a static parent, which would look something like this:

jQuery($ => {
  $(document).on('click', '.user_bookmark', function(e) {
    e.preventDefault();
    let post_id = $(this).data("post_id");
    let nonce = $(this).data("nonce");

    console.log(post_id, nonce);
    console.log('ajax request here...');
  });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM