Using selectors and $(this) in Jquery Ajax

前端 未结 2 797
萌比男神i
萌比男神i 2021-01-23 14:44

I have event mouseenter link with get ajax request, I want to get selector $(this) of link and get attribute. I\'m use context of setting

相关标签:
2条回答
  • 2021-01-23 15:42

    If you want this inside the callback to refer to the a element (i.e. the element the handler was bound to), use

    context: this
    

    instead of

    context: $(this).parent().get(0)
    

    $(this).parent().get(0) selects the parent of the a element, which is a li element, which doesn't seem to have a data-title attribute.

    From the documentation:

    context
    This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

    $.ajax({
      url: "test.html",
      context: document.body
    }).done(function() {
      $( this ).addClass( "done" );
    });
    

    See also $(this) inside of AJAX success not working

    0 讨论(0)
  • 2021-01-23 15:47

    try assigning "this" to a variable:

    jQuery(document).ready(function($) {
      var request;
      $('a[rel="bookmark"]').mouseenter(function() { 
      var that=this;
      // other stuff
      request = $.ajax({
          dataType: "JSON",
          url: '<?php echo admin_url("admin-ajax.php"); ?>',
          data: {"action": "our_ajax_function", "id": dataId},
          success: function(data){
              // other stuff
              var gettitle = $(that).data('title','Permanent Link to ');
          }
      })
    });
    

    also while using the HTML5 Data Attribute you can get or modify the data in jQuery with the data() function:

    $(that).data('title','Permanent Link to '); //sets the "data-title" of the selected element as "Permanent Link to "
    
    0 讨论(0)
提交回复
热议问题