JQuery加载帮助

时间:2010-04-01 15:47:09

标签: jquery

我正在尝试使用load()将一些html放入页面上的div中。我有很多像这样的链接:

    <div id="slideshow">
        <div id="slides">
        <div class="projects">
            <a href="work/mobus.html" title="Mobus Fabrics Website">
                <img src="images/work/mobus.jpg" alt="Mobus Fabrics Website" width="280" height="100" />
            </a>

            <a href="work/eglin.html" title="Eglin Ltd Website">
                <img src="images/work/eglin.jpg" alt="Eglin Ltd Website" width="280" height="100" />
            </a>

            <a href="work/first-brands.html" title="First Brands Website">
                <img src="images/work/first-brands.jpg" alt="First Brands Website" width="280" height="100" />
            </a>
        </div>

        <a id="prev"></a>
        <a id="next"></a>
    </div>

我的jquery代码如下所示:

$('.projects a').click(function() {
    $('#work').load(this.href);
});

问题是当点击html放在#work div中时html被加载到另一个页面中。请任何人帮忙吗?

2 个答案:

答案 0 :(得分:6)

您需要阻止默认操作停止加载的href:

$('.projects a').click(function(event) {
    $('#work').load(this.href);

    event.preventDefault();
});

您可能也会看到人们通过以下方式实现相同目标:

$('.projects a').click(function(event) {
    $('#work').load(this.href);

    return false;
});

但是,此方法将停止事件冒泡,以及阻止默认操作。如果您有任何delegatelive方法在DOM树的上方监听同一事件,那么执行return false将停止调用这些处理程序。

编辑:对于回调函数:

$('.projects a').click(function(event) {
    $('#work').load(this.href, function (text) {
        alert("This loaded: " + text);
    });

    event.preventDefault();
});

答案 1 :(得分:1)

您必须阻止事件链接..浏览器最终会跟随链接。

请参阅preventDefault