小编典典

在Jquery Ajax中使用选择器和$(this)

ajax

我有mouseenter获取ajax请求的事件链接,我想获取$(this)链接的选择器并获取属性。我正在context为AJAX回调设置ajax。

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

但是我得到这个错误

Uncaught TypeError: Cannot read property 'replace' of undefined

我有mouseenter获取ajax请求的事件链接,我想获取$(this)链接的选择器并获取属性。我正在context为AJAX回调设置ajax。

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

但是我得到这个错误

Uncaught TypeError: Cannot read property 'replace' of undefined

的HTML

<ul>
   <li>
    <a href="http://localhost/area-no-kishi/" rel="bookmark" data-title="Permanent Link To Area no Kishi" data-id="4126" target="_blank">Area no Kishi </a>
   </li>
   <li>
    <a href="http://localhost/aria-the-scarlet-ammo-hidan-no-arai/" rel="bookmark" data-title="Permanent Link To Permanent Link to Aria the Scarlet Ammo ( Hidan No Aria )" data-id="1081" target="_blank">Aria the Scarlet Ammo ( Hidan No Aria ) </a>
   </li>
</ul>

阅读 248

收藏
2020-07-26

共1个答案

小编典典

如果要this在回调内部引用该a元素(即处理程序绑定到的元素),请使用

context: this

代替

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

$(this).parent().get(0)选择a元素的父元素,即li元素似乎没有data-title属性。

文档中

context

该对象将成为所有与Ajax相关的回调的上下文。默认情况下,上下文是一个对象,代表调用中使用的ajax设置($.ajaxSettings与传递给的设置合并
$.ajax)。例如,将DOM元素指定为上下文将使该上下文成为请求的完整回调,如下所示:

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

另请参阅AJAX成功内的$(this)无法正常工作

2020-07-26