在我的页面上,我希望用户能够mouseover
td
元素,让页面对服务器进行 Ajax 调用,然后附加一个 title
属性添加到 td
以用作用户在页面上剩余时间的工具提示。
页面需要检索的信息非常基本,因此没有什么太复杂的......但是我无法获得代码来将我从 Ajax 调用接收到的 data
附加到 td
元素。
Jquery/Ajax
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '@Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title'));
});
不幸的是,我可以在控制台中看到 'ajax'
条目,后跟我期望的 data
对象的确切值,但是 undefined
显示为来自最终 console.log
语句的 td
title
属性的值(mouseover 结束
)。
HTML/Razor
<td class="ChannelCodeDesc">
@Html.DisplayFor(model => model.displayForPaging[i].ChannelCode)
@Html.HiddenFor(model => model.displayForPaging[i].ChannelCode)
</td>
Ajax Controller 方法
public JsonResult GetDesc(string channel)
{
var description = (from c in db.Channel
where c.ChannelCode.Equals(channel)
select c.ChannelLongDescription).FirstOrDefault();
return Json(description, JsonRequestBehavior.AllowGet);
}
最佳答案
问题是success函数中的this
对象不是td元素。默认情况下,jquery ajax 回调的上下文被设置为表示 ajax 选项的对象。但是,您可以使用 context option 更改它:
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '@Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
context: this, //make sure "this" inside the success callback is the td element
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title')); });
关于javascript - jQuery 不附加标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23642668/