使用 jQuery 设置工具提示文本

Set tooltip text with jQuery

本文关键字:文本 工具提示 设置 jQuery 使用      更新时间:2023-09-26

我有以下代码:

var text = "";
$.ajax({
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    type: "POST",
    url: DataReview.BASE + "/Encryption/FetchLatestEditBy",
    data: JSON.stringify({
        "ExtendedReport_id": dataRow["ExtendedReport_id"],
        "Report_id": dataRow["Report_id"]
    }),
    success: function (data) {
        text = data.ResultData;
    },
    error: function (data) {
        console.log(data);
    }
});
setTimeout(function () {
    console.log(text); //This displays the value
    $(this).attr('data-toggle', 'tooltip');
    $(this).attr('title', text);
}, 1000);

如您所见,我正在尝试在 setTimeout 函数中设置工具提示文本。但它不会出现。当我用一些虚拟文本替换text变量时,它可以工作。但是变量值不起作用。

使用超时时,this将在窗口范围内,而不是元素中。因此,您实际上是在向窗口添加属性。

其次,不能保证 ajax 调用会完成,或者您可能在使用超时在 Ajax 调用后等待太久。您应该在 Ajax 调用的成功回调中设置属性。

第三,您可能需要手动触发工具提示,以便获取更新的数据。

var elem = $(this);
$.ajax({
    /* your code here, removed to simplify answer*/
    success: function (data) {
        elem.attr('data-toggle', 'tooltip');
        elem.attr('title', text);
        elem.tooltip().tooltip("show"); // might need to change this line based on actual library
    }
});

我假设您的 ajax 成功需要更多时间,因此在成功函数中设置"文本"变量值之前首先调用 setTimeout 函数。尝试在 onsuccess ajax 函数中调用函数。

var text = "";
$.ajax({
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    type: "POST",
    url: DataReview.BASE + "/Encryption/FetchLatestEditBy",
    data: JSON.stringify({
        "ExtendedReport_id": dataRow["ExtendedReport_id"],
        "Report_id": dataRow["Report_id"]
    }),
   success: function (data) {
      text = data.ResultData;
      settooltiptext();
   },
   error: function (data) {
       console.log(data);
   }
});
function settooltiptext()
{
    console.log(text); //This displays the value
    $(this).attr('data-toggle', 'tooltip');
    $(this).attr('title', text);
}