使用 ajax 将鼠标悬停时更改标签文本

Change label text on mouse over with ajax

本文关键字:标签 文本 悬停 ajax 鼠标 使用      更新时间:2023-09-26

我想在鼠标悬停时更改标签的值。这是我到目前为止所做的:

$(function () {
    var hoverOff = "";
    $("[id*=GV] td").hover(function () {
        hoverOff = $("label", $(this).closest("td")).text();
        $.ajax({
            type: "POST",
            url: "MyMethode.aspx/GetNewValue?text=" + hoverOff,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $("label", $(this).closest("td")).html(data.d);
                }
            });
        },
        function () {
            $("label", $(this).closest("td")).html(hoverOff);
        }
);});

一开始,我将当前文本保存在 hoverOff 中,并将该值发送到返回新值的方法 GetNewValue,在 ajax 成功中,我想将该值应用于标签。问题是标签的文本永远不会改变,尽管 data.d 包含新文本。我应该使用其他东西而不是 .html((吗?

ajax 回调中的this不是指当前悬停的 TD,而是指向 jqXHR 对象。您可以使用$.ajax上下文选项:

context: this,

顺便说一句,$(this).closest("td")是完全无关紧要的,因为显然,即使您有嵌套的 TD,$(this).closest("td")也会始终返回当前的 TD,因此您可以使用this

hoverOff = $("label", this).text();

data: "{}",可以data: {},,在这里设置字符串没有意义。>>因为您将 contentype 设置为 JSON

这是一个

上下文问题,你不能在成功函数中使用this,试试这段代码:

$(function () {
    var hoverOff = "";
    $("[id*=GV] td").hover(function () {
        var label = $("label", $(this).closest("td"));
        hoverOff = label.text();
        $.ajax({
            type: "POST",
            url: "MyMethode.aspx/GetNewValue?text=" + hoverOff,
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                label.html(data.d);
                }
            });
        },
        function () {
            label.html(hoverOff);
        }
);});
您可以使用

此解决方案 https://stackoverflow.com/a/10701170/3421811

$('.btn').hover(
function() {
    var $this = $(this); // caching $(this)
    $this.data('initialText', $this.text());
    $this.text("I'm replaced!");
},
function() {
    var $this = $(this); // caching $(this)
    $this.text($this.data('initialText'));
}
);