...但是当我尝试在theDiv“注入”,我得到了一个空白页面。
您需要取消链接的默认操作;否则,链接将被遵循。将return false
添加到您的点击处理程序的末尾,或将e.preventDefault();
添加到它。例如,这样的:
$('a[rel*=ajax]').click(function(e)
{
ajaxLink = $(this).attr('href')+"?ajax=true";
theDiv = $(this).parents(".post");
$.get(ajaxLink,function(data, textStatus){ $(theDiv).replaceWith(data); });
return false; // This both prevents the default and stops bubbling
});
或
$('a[rel*=ajax]').click(function(e)
{
ajaxLink = $(this).attr('href')+"?ajax=true";
theDiv = $(this).parents(".post");
$.get(ajaxLink,function(data, textStatus){ $(theDiv).replaceWith(data); });
e.preventDefault(); // This just prevents the default, doesn't stop bubbling
});
另外:
的引用代码使用从父范围ajaxLink
和theDiv
变量(如果他们没有宣布任何地方,他们'implicit global variables)。在显示的代码运行之后但在ajax调用完成之前,是否可以改变theDiv
的值?这意味着当ajax调用完成时,它将使用新值theDiv
而不是旧值。
在任何情况下,似乎没有任何理由的代码应该是使用从父范围变量,我建议让他们本地的功能:
$('a[rel*=ajax]').click(function(e)
{
var ajaxLink = $(this).attr('href')+"?ajax=true";
// ^-- This is the new bit, the `var`
var theDiv = $(this).parents(".post");
// ^-- And this one
$.get(ajaxLink,function(data, textStatus){ $(theDiv).replaceWith(data); });
});
作为一个单独的问题,你确定要replaceWith
(这将取代具有类post
父),而不是html
(这只会替换其内容)?
但也没有理由再次呼吁theDiv
$
; parents
已经返回一个jQuery对象。所以:
$('a[rel*=ajax]').click(function(e)
{
var ajaxLink = $(this).attr('href')+"?ajax=true";
var theDiv = $(this).parents(".post");
$.get(ajaxLink,function(data, textStatus){ theDiv.replaceWith(data); });
// ^-- No need for $ here
});
最后:你可以看一下load
功能,它从服务器加载HTML并更新结果的元素的内容。
哪个版本的IE浏览器? – 2010-11-09 17:18:26
不幸的是每一个版本 – Luke 2010-11-09 17:37:14