我在 DOM 中有一个可拖动的元素,当它被点击时,我想获取 x/y 坐标(此示例中未显示,但用于未来)和淡入的工具提示的高度。源文本工具提示是一个 AJAX 调用,可以是可变长度。我目前的问题是该shown.bs.tooltip
事件仅在second
单击触发元素时触发。代码:
$('#click').draggable();
$(document.body).on('click', function () {
tooltipManager.title();
});
$('#click').on('shown.bs.tooltip', function () {
console.log('from getHeight: ' + getHeight($('.tooltip')));
});
var tooltipManager = {
title: function () {
//ajax code to get title from database
$.ajax({
type: "POST",
contentType: "application/json",
url: "Service.asmx/GetDrugs",
dataType: "json",
success: function (data) {
//bootstrap uses the title attribute to set the html inside the tooltip
//here it's set to the results of the AJAX
var $tooltipData = prettyTooltip(data.d);
var offset = $('#click').offset();
var windowSize = [
width = $(window).width(),
height = $(window).height()
]
//this fires on the first click
console.log(window.width);
console.log(offset.top);
$('#click').tooltip({
trigger: 'click',
html: true,
placement: tooltipManager.placement.setPlacement(data.d),
title: $tooltipData.html()
//it seems to me that it would be better design to call the tooltipManager
//setPlacement function, but since it's an async request, it fails
});
//if I add click() at the above line I get an infinite loop of AJAX calls
},
error: function (xhr) {
console.log('failed: ' + xhr.status);
}
});
},
placement: {
left: 'left',
top: 'top',
right: 'right',
bottom: 'bottom',
//if the value of getHeight is over a certain amount
//I want to change the position of the tooltip
setPlacement: function () {
var height = getHeight($('.tooltip'));
var place = '';
if (height < 150) {
place = 'right';
}
else {
place = 'left'
}
return place;
}
}
}
//not sure if this is good design to have this not a property of the tooltipManager object
//this works currently for placing the tooltip in the correct position
function prettyTooltip(data) {
var $div = $('<div>');
for (var i = 0; i < data.length; i++) {
var $p = $('<p>').text(data[i]).appendTo($div);
}
return $div;
}
function getHeight(el) {
return $(el).height();
}
如果我使用该one
方法而不是on
在代码指示的地方添加一个 click() ,则工具提示会在第一次单击时触发,但在一次性单击后我无法获得偏移量。如何确保保留所有当前功能并且不需要单击两次即可显示工具提示?
编辑:小提琴