[英]Setting data-content and displaying popover
我正在嘗試使用jquery的ajax從資源中獲取數據然后我嘗試使用此數據來填充引導彈出窗口,如下所示:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
並且檢索數據的功能是:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
發生的事情是當我點擊時彈出窗口沒有顯示,但是如果我稍后懸停元素它將顯示彈出窗口,但沒有內容( data-content
屬性)。 如果我在success
回調中放置一個alert()
,它將顯示返回的數據。
知道為什么會這樣嗎? 謝謝!
在您的成功回調中, this
不再綁定到與get_data_for_popover_and_display()
的其余部分相同的值。
別擔心! this
關鍵字很毛茸茸; 誤解其價值是JavaScript中的一個常見錯誤。
您可以通過保持一個參考解決這個this
將其分配給一個變量:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
或者你可以寫var that = this;
到處使用$(that)
。 更多的解決方案和背景在這里 。
除了上面的答案,不要忘記根據$ .ajax()文檔,你可以使用context參數來實現相同的結果,而不需要額外的變量聲明:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.