在Jquery Ajax中使用选择器和$(this)
我有事件mouseenter
链接与获取ajax请求,我想获得选择器$(this)
的链接和获取属性。 我使用为AJAX回调设置ajax的context
。
jQuery(document).ready(function($) { var request; $('a[rel="bookmark"]').mouseenter(function() { // other stuff request = $.ajax({ dataType: "JSON", url: '', 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)
的链接和获取属性。 我使用为AJAX回调设置ajax的context
。
jQuery(document).ready(function($) { var request; $('a[rel="bookmark"]').mouseenter(function() { // other stuff request = $.ajax({ dataType: "JSON", url: '', 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
如果你想在回调中引用a
元素(即处理程序绑定的元素),请使用
context: this
代替
context: $(this).parent().get(0)
$(this).parent().get(0)
选择a
元素的父元素,它是一个li
元素,它似乎没有data-title
属性。
从文档 :
上下文
此对象将成为所有与Ajax相关的回调的上下文。 默认情况下,上下文是一个对象,表示调用中使用的ajax设置($.ajaxSettings
与传递给$.ajax
的设置合并)。 例如,将DOM元素指定为上下文将使得请求的完整回调的上下文,如下所示:$.ajax({ url: "test.html", context: document.body }).done(function() { $( this ).addClass( "done" ); });
另见$(this)内部的AJAX成功无效
尝试将“this”分配给变量:
jQuery(document).ready(function($) { var request; $('a[rel="bookmark"]').mouseenter(function() { var that=this; // other stuff request = $.ajax({ dataType: "JSON", url: '', data: {"action": "our_ajax_function", "id": dataId}, success: function(data){ // other stuff var gettitle = $(that).data('title','Permanent Link to '); } }) });
在使用HTML5数据属性时,您可以使用data()
函数获取或修改jQuery中的data()
:
$(that).data('title','Permanent Link to '); //sets the "data-title" of the selected element as "Permanent Link to "
- 以编程方式查看客户端浏览器是否支持PUT / DELETE方法
- 使用JSONP调用ajax返回错误Uncaught ReferenceError:未定义jquery19102754115150310099_1392753827782
- 在DataTables中为渲染选择设置初始选定选项
- 无法从XMLHttpRequest触发单击
- Sys.ParameterCountException:参数计数不匹配
- 如何在一个页面上运行多个ajax调用
- 如何在没有取消的情况下在页面卸载时发送AJAX请求?
- 通过滚动触发’查看更多’按钮
- 使用jquery偶尔的ajax响应错误{readyState = 0,status = 0,statusText =“error”}