使用AJAX编写内部链接

发布于 2024-12-13 00:17:45 字数 836 浏览 3 评论 0原文

我正在尝试编写一些我的第一个 jquery 脚本,但遇到了一些问题...... 我的页面有很长的文本,有很多内部链接( Foo )。我希望当您单击其中一个 .internal 链接时,href 路径将在

内打开。

var InternalLink = function() {
    $(".internal").click(function(){
        var path =  $(this).attr("href");
        $.ajax({
            url: "path",
            success: function(data) {
                $('#article').html(data);
            }
        });
    });    
};

我编写了如下所示的代码,它工作得很好,但我试图将代码推广到具有内部类的每个链接:

$("#article_01").click(function(){
    $.ajax({
        url: 'contents/article_01.htm',
        success: function(data) {
            $('#article').html(data);
        }
    });
});

I am trying to write some of my first jquery scripts but I'm having some problem...
My page have a long text with lot of internal links (
<a href="/contents/Foo.htm" class=.internal>Foo</a>
). I'd like that when you click on one of the .internal links, the href path will be opened inside the <div id="article">.

var InternalLink = function() {
    $(".internal").click(function(){
        var path =  $(this).attr("href");
        $.ajax({
            url: "path",
            success: function(data) {
                $('#article').html(data);
            }
        });
    });    
};

I wrote the code shown below and it work perfectly but I am trying to generalize the code to every link with internal class:

$("#article_01").click(function(){
    $.ajax({
        url: 'contents/article_01.htm',
        success: function(data) {
            $('#article').html(data);
        }
    });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

剩一世无双 2024-12-20 00:17:45
<a href="/contents/Foo.htm" class="internal" data-ref="article_01">Foo</a>

JS:

$(".internal").click(function(){
    var path =  this.href;
    var div = $(this).data('ref');
    $.ajax({
        url: path,
        success: function(data) {
            $('#'+div).html(data);
        }
    });
    return false; // so the link does *not* follow through
});    

所以现在您所要做的就是更改 data-ref 以指向您希望 html 加载到其中的 div。

<a href="/contents/Foo.htm" class="internal" data-ref="article_01">Foo</a>

JS:

$(".internal").click(function(){
    var path =  this.href;
    var div = $(this).data('ref');
    $.ajax({
        url: path,
        success: function(data) {
            $('#'+div).html(data);
        }
    });
    return false; // so the link does *not* follow through
});    

So now all you have to do is change the data-ref to point to the div you want the html to load inside of.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文