[英]Using selectors and $(this) in Jquery Ajax
我有事件mouseenter
鏈接與獲取ajax請求,我想獲得選擇器$(this)
的鏈接和獲取屬性。 我使用為AJAX回調設置ajax的context
。
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)
的鏈接和獲取屬性。 我使用為AJAX回調設置ajax的context
。
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>
嘗試將“this”分配給變量:
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 ');
}
})
});
在使用HTML5數據屬性時,您可以使用data()
函數獲取或修改jQuery中的data()
:
$(that).data('title','Permanent Link to '); //sets the "data-title" of the selected element as "Permanent Link to "
如果你想this
回調里面指的是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" ); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.