在我的页面上,我希望用户能够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
显示为最终td
语句中的title
console.log
属性(mouseover
的结尾)。
HTML /剃须刀
<td class="ChannelCodeDesc">
@Html.DisplayFor(model => model.displayForPaging[i].ChannelCode)
@Html.HiddenFor(model => model.displayForPaging[i].ChannelCode)
</td>
Ajax控制器方法
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);
}
答案 0 :(得分:1)
最终的console.log语句显示未定义,因为它发生在AJAX请求完成之前(因为AJAX请求是异步的)。
另外,td不能有title属性,可能需要查看其他选项: how to apply style to 'title' attribute of 'td' tag
其他人已经声明,不能在这样的ajax成功函数中使用$ this。
答案 1 :(得分:1)
我假设Ajax返回的数据有效.... 成功中的$(this)不再引用td了。
在ajax调用之外执行此操作:
var me = $(this);
然后在您的成功代码中执行以下操作:
me.attr('title', data);
答案 2 :(得分:1)
问题是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')); });